What is Spring Bean Definition & Spring Bean Scope?

In the previous article, we have seen How to inject collection types in Spring you can check it here How to Inject Collection using Dependency Injection in Spring. In this article, we will understand what exactly is Spring Bean, and the Scope of the Bean.

What is Spring Bean?

The Spring Framework has a container called IOC Container whose responsibility is to create an Object. These objects are nothing but the spring beans.

  • The Spring beans are created by the IOC container with the help of configuration metadata that you supply to the IOC container using a config file. 
  • We supply metadata in the form of <bean> element.
  • In IOC container these Beans are regarded as BeanDefinition objects.

Let us see the metadata that makes up bean definition. Following are the properties with descriptions.

Property

Description

Class It tells which class to instantiate
Name It describes the identifier for the created bean.
Scope It describes the scope of the created object.
Constructor arguments It injects constructor dependencies.
Properties It injects setter method dependencies Injection
Autowiring mode It injects reference dependencies
Lazy-initialization Mode It tells the IOC container to create an object when it is first requested rather than at the startUp.
Initialization method It is a method that is called when all the properties are set by the container.
Destruction method It is a method which is called when the beans are destroyed.

Till now we have seen XML-based configuration metadata is provided to the IOC Container. But is this the only way? The answer is No. We can provide the configuration metadata in the following two more ways.

  • Annotation-based Configuration
  • Java-based Configuration

Both these configuration we will see in the coming article. Now, let us see sample Bean Definition using XML-based configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
  <!--Simple Bean Definition -->
  <bean id="#" class="#"></bean>
  <!--Simple Bean Definition with scope -->
  <bean id="#" class="#" scope="prototype"></bean>
  <!--Simple Bean Definition with lazy Initialization -->
  <bean id="#" class="#" lazy-init="true"></bean>
  <!--Simple Bean Definition Initialization Method -->
  <bean id="#" class="#" init-method="#"></bean>
  <!--Simple Bean Definition Destruction method -->
  <bean id="#" class="#" destroy-method="#"></bean>
</beans>

Thus, this is a way we define Bean Definition for more clarity you can view the example of the previous article like how configuration is done in the beans.xml file.

What is Bean Scopes?

While creating a bean definition, we can create as many object instances from a single class. Along with this, We can control the scope of the objects created from a particular bean definition. Spring framework provides the following Scopes.

Scope

Description

singleton It creates a single instance for each Spring IOC container
prototype It describes a single bean definition can have any number of the object instance
request It scopes a single bean definition to the HTTP request.
session It scopes a single bean definition to the HTTP session.
application It scopes a single bean definition to the ServletContext
websocket It scopes a single bean definition to the WebSocket.

Let us discuss the first two scope i.e.

  • singleton
  • prototype

Singleton Scope

From Singleton, we mean a single object. When we set the scope to singleton, the IOC container creates only a single instance of the object defined by the bean definition. Let’s take an example to use this scope.

Create a Spring Project Go to File> New > Other > Search maven > Select Maven Project > Next > Search Filter org.apche.maven.archetypes/webapp > Next > Enter Group Id & Archetype id > Finish.

  • Create a class Computer with computer config attribute

Computer.java

package com.codedec.di;

public class Computer {

  private String ComputerConfig;

  public String getComputerConfig() {
    return ComputerConfig;
  }

  public void setComputerConfig(String computerConfig) {
    ComputerConfig = computerConfig;
  }

}
  • create a beans.xml file with <bean> element
  • The IOC container will create the object of the class specified here with an identifier specified in id.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="computer" class="com.codedec.di.Computer"
    scope="singleton">
  </bean>

</beans>
  • On line no:7, we have specified the scope “singleton” i.e each time the IOC container will give us the same object. By default, the scope is a singleton.
  • create an App.java file, and create the object of ApplicationContext, get the bean from it, and call hashCode() method.

App.java

package com.codedec.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Computer c1 = context.getBean("computer", Computer.class);
    System.out.println(c1.hashCode());
    
    Computer c2 = context.getBean("computer", Computer.class);
    System.out.println(c2.hashCode());
  }

}

Output

1153447573
1153447573

Here, we can see both the hashcode are the same because when we first get the bean the container creates the object but when on line no. 13 when we call the getBean() method container didn’t create the object again. It gave us the already created object. So, in this way Singleton’s scope is implemented.

Prototype Scope

The prototype scope means every time a new instance of an object is created. The Spring IOC Container will create a new object whenever we will call the getBean() method. Let us take an example to use this scope.

Note: Follow all the steps that we have seen in Singleton Scope Just one change we have to do is that just alter the beans.xml file and change the scope to prototype.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="computer" class="com.codedec.di.Computer"
    scope="prototype">
  </bean>

</beans>

Just run the App.java and view the hashCode value.

757004314
1279271200

Here, we can see both the hashcode are different because when we first get the bean the container creates the object but when on line no. 13 when we call the getBean() method container it creates the object again. It gave us the newly created object. So, in this way Prototype scope is implemented.

Thus, this was all about the Scope of Bean.

Thus, in this article, we have seen the Bean Definition and bean Scopes in detail. In the next article of this tutorial, we will see what is the life cycle of Bean.