Java ProgrammingLearn About Bean Scopes in Spring Framework

Learn About Bean Scopes in Spring Framework

In this chapter, we are going to discuss about the Bean scopes in spring framework. The configuration metadata file in spring allows to define the scope of the bean which is created through an IOC container. When we define a element in XML, then there we have the option to declare the scope of that bean. If we want that container to produce a new bean instance each time that bean is needed, then we can declare the scope of that bean as ‘prototype’ but if want to keep just a single instance of bean and want to use the same bean when it is needed then we can declare the scope of that bean as ‘singleton’ in XML configuration file. There are five bean scopes which are supported by the Spring Framework, out of which three scopes i.e. request, session and global-session are available only for use in a web-aware ApplicationContext.

Types of Bean Scope in Spring Framework

S No.

Scope

Definition

1.

singleton

This attribute value allows you to scope the bean definition to a single instance per Spring IoC container. If scope is not defined then it will be singleton by default.

2.

prototype

This attribute value allows you to scope a single bean definition to have any as many numbers of object instances as required.

3.

request

This attribute value allows you to scope a bean definition to an HTTP request. It is valid only in the case of context of a web-aware Spring ApplicationContext.

4.

session

This attribute value allows you to scope a bean definition to an HTTP session. It is valid only in the case of context of a web-aware Spring ApplicationContext.

5.

global-session

This attribute value allows you to scope a bean definition to a global HTTP session. It is valid only in the case of context of a web-aware Spring ApplicationContext.

Singleton Scope
If the scope attribute value is set to singleton, then the Spring IoC container will create exactly one instance of the object per spring IOC container. Spring container will store this single instance in a cache of such singleton beans, and all following requests and references for that named bean will get the cached object as return bean. If scope attribute value is not defined in the configuration metadata for a bean, then it will be singleton by default. It is recommended to use the singleton scope for stateless beans.

We can define the scope property to singleton in the bean configuration file through the following code snippet.

<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Example on Singleton scoped Bean
We can create singleton scoped bean application through the following steps.
1. Create a Maven project using eclipse as we have done in the earlier chapter of this tutorial.
2. Next, add the required spring framework dependencies in pom.xml file
3. Next, create a Java class “HelloApplicationContext.java” under “src/main/java” directory of Maven Project which has a property as “msg” and associated setter and getter methods to this property as shown below.

package com.eduonix.springframework.singleton.scope;

/**
 * 
 * @author Aparajita
 *
 */
public class HelloApplicationContext {

	   private String msg;  
	   
	   public void setMsg(String msg){ 
	      this.msg  = msg; 
	   }  
	   public void getMsg (){ 
	      System.out.println("Response Message : " + msg); 
	   } 
}

4. Create a spring ApplicationContext container configuration file “bean-factory-config.xml” under “src/main/resources” directory of Maven Project where we have defined the configuration metadata along with scope=”singleton” for IOC container as shown below.

<?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
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "helloApplicationContext" class = "com.eduonix.springframework.singleton.scope.HelloApplicationContext" scope="singleton">
      <property name = "msg" value = "This is singleton Bean scope Demonstration!"/>
   </bean>

</beans>

5. Lastly, create a Java class “App.java” under “src/main/java” directory of Maven Project where we are going to load the ApplicationContext configuration through FileSystemXmlApplicationContext class (here configuration file path is provided) and through ApplicationContext container we are going to instantiate the Bean object “HelloApplicationContext” and call the ‘setMsg’ method to set the property value as “This is an object A!”. Next, we are calling ‘getMsg’ method to display the value of property which is recently set. Now, when we again call ‘getMsg’ method then it will display the same value which we set last time. The reason behind it that there exists a singleton bean (i.e. single object).

package com.eduonix.springframework.singleton.scope;

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

/**
 * 
 * @author Aparajita
 *
 */
public class App {
	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext(
				"C:/work/IOC Containers/springframework.singleton.scope/src/main/resources/bean-factory-config.xml");

		HelloApplicationContext objA = (HelloApplicationContext) context.getBean("helloApplicationContext");

		objA.setMsg ("This is an object A!");
		objA.getMsg();

		HelloApplicationContext objB = (HelloApplicationContext) context.getBean("helloApplicationContext");
		objB.getMsg ();

	}
}

Output: –
When we will execute the App.java class as a Java application in eclipse, then we will observe the following output.

Dec 02, 2017 10:17:42 PM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@377dca04: startup date [Sat Dec 02 22:17:42 EST 2017]; root of context hierarchy
Dec 02, 2017 10:17:42 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\work\IOC Containers\springframework.singleton.scope\src\main\resources\bean-factory-config.xml]
Response Message: This is an object A!
Response Message: This is an object A!

Singleton Scope
When we set scope to prototype for a bean in the configuration file, then the Spring IoC container will always create a new bean instance of the object every time a request is made for that bean. It is recommended to use the prototype scope for all state-full beans.

We can define the scope property to prototype in the bean configuration file through the following code snippet.

<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Example on Singleton scoped Bean
We can create prototyped scoped bean application through the following steps.
1. Create a Maven project using eclipse as we have done in the earlier chapter of this tutorial.
2. Next, add the required spring framework dependencies in pom.xml file
3. Next, create a Java class “HelloApplicationContext.java” under “src/main/java” directory of Maven Project which has a property as “msg” and associated setter and getter methods to this property as shown below.

package com.eduonix.springframework.prototype.scope;

/**
 * 
 * @author Aparajita
 *
 */
public class HelloApplicationContext {

	   private String msg;  
	   
	   public void setMsg(String msg){ 
	      this.msg  = msg; 
	   }  
	   public void getMsg (){ 
	      System.out.println("Response Message : " + msg); 
	   } 
}

4. Create a spring ApplicationContext container configuration file “bean-factory-config.xml” under “src/main/resources” directory of Maven Project where we have defined the configuration metadata along with scope=”prototype” for IOC container as shown below.
The bean-factory-config.xml file

<?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
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "helloApplicationContext" class = "com.eduonix.springframework.prototype.scope.HelloApplicationContext" scope="prototype">
      <property name = "msg" value = "Welcome to Prototype Bean scope Demonstration!"/>
   </bean>

</beans>

5. Lastly, create a Java class “App.java” under “src/main/java” directory of Maven Project where we are going to load the ApplicationContext configuration through FileSystemXmlApplicationContext class (here configuration file path is provided) and through ApplicationContext container we are going to instantiate the Bean object “HelloApplicationContext” and call the ‘setMsg’ method to set the property value as “This is an object A!”. Next, we are calling ‘getMsg’ method to display the value of property which is recently set. Now, when we again call ‘getMsg’ method then it will display the different property value which is the default value that we set in the configuration metadata for any new bean object for prototype scope

package com.eduonix.springframework.prototype.scope;

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

/**
 * 
 * @author Aparajita
 *
 */
public class App {
	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext(
				"C:/work/IOC Containers/springframework.prototype.scope/src/main/resources/bean-factory-config.xml");

		HelloApplicationContext objA = (HelloApplicationContext) context.getBean("helloApplicationContext");

		objA.setMsg("This is an object A");
		objA.getMsg();

		HelloApplicationContext objB = (HelloApplicationContext) context.getBean("helloApplicationContext");
		objB.getMsg();
	}
}

Output: –
When we will execute the App.java class as a Java application in eclipse then, we will observe the following output.

Dec 02, 2017 10:34:11 PM org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@377dca04: startup date [Sat Dec 02 22:34:11 EST 2017]; root of context hierarchy
Dec 02, 2017 10:34:11 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [C:\work\IOC Containers\springframework.prototype.scope\src\main\resources\bean-factory-config.xml]
Response Message: This is an object A
Response Message: Welcome to Prototype Bean scope Demonstration!

Source Code for this Types of Ben Scopes in Spring Framework

Conclusion: –
In this tutorial, we discussed about the different types of bean scope in spring framework along with the suitable examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -