Spring Bean Scopes and Lifecycle

What is Scope?

A scope refers to the life cycle of a bean. For example how long does the bean live, how many instances are created for the bean and how the bean is shared in the spring environment etc.


Spring framework supports six type of scopes that are described below:

  1. singleton
  2. prototype
  3. request
  4. session
  5. global-session
  6. application

What is Scope?

A scope refers to the life cycle of a bean. For example how long does the bean live, how many instances are created for the bean and how the bean is shared in the spring environment etc.


Spring framework supports six type of scopes that are described below:

  1. singleton
  2. prototype
  3. request
  4. session
  5. global-session
  6. application


singleton Scope :

This is default bean scope and Spring container creates only one instance of the bean.It is cached in memory. All requests for the bean will return a shared reference to the same bean.

If In the bean definition the scope is not given, then by default singleton scope is assumed. In a given Spring container a singleton scoped bean will be instantiated only once and the same will be used for its lifetime.Singleton scoped beans are mostly used for stateless beans.


How to define the bean scope

We can define the scope of a bean in two ways.

Singleton Scope using XML

In singleton bean scope, we need to assign singleton value to the attribute scope.

<bean id="address" class="com.jwt.bean.Address" scope="singleton">
      <constructor-arg name="city" value="Bangalore"/>
     </bean>  

Singleton Scope using @Scope Annotation

We can define the bean with singleton scope by using @Scope annotation.

@Scope("singleton")
public class Address {
	
}  


Singleton Scope Example

Create a java project and add the spring libraries as described in Spring Hello World Example.

  • Employee.java
  • Spring-Context.xml
  • TestSingletonBean.java

Employee.java

package com.jwt.spring;

public class Employee {

	private String name;
	private String designation;

	// getter's & setter's
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}
}


Spring-Context.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" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.0.xsd">

	<bean id="employee" class="com.jwt.spring.Employee" scope="singleton">
	</bean>

</beans>


TestSingletonBean.java

package com.jwt.spring;

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

public class TestSingletonBean {

	public static void main(String[] args) {

		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"com/jwt/spring/SpringContext.xml");

		// employee 1 - retrieve employee bean
		Employee employee1 = (Employee) applicationContext.getBean("employee");

		// setting values using employee1 bean
		employee1.setName("Ravi Raj");
		employee1.setDesignation("Technical Lead");

		// print values in console using employee1 bean
		System.out.println("\nPrinting values in console using employee1 bean");
		System.out.println("Name \t\t: " + employee1.getName());
		System.out.println("Designation \t: " + employee1.getDesignation());

		// employee 2 - retrieve again the same bean
		Employee employee2 = (Employee) applicationContext.getBean("employee");

		// print values in console using employee2 bean
		System.out
				.println("\n\nPrinting values in console using employee2 bean");
		System.out.println("Name \t\t: " + employee2.getName());
		System.out.println("Designation \t: " + employee2.getDesignation());
		System.out.println("employee1 hash Code : " + employee1.hashCode());
		System.out.println("employee2 hash Code : " + employee2.hashCode());

		System.out
				.println("Is Singleton Bean employee1 and singleton employee2 are same ? "
						+ (employee1 == employee2));
	}
}

In the Test class we are calling getBean("employee"); method which returns the single bean instance named employee1.In next step set the values of employee member variables (name/designation) using above returned employee1 instance. Print the values in the console output using employee1 bean.

Again, retrieve the employee bean for another employee i.e.; emplopyee2 bean and try to print the values in the console for employee2; it prints the same values as that of the employee1 which was actually set by employee1 bean. Also You can see in output hashCode of both the instances are same and == operator returns true as well which confirms that both beans are same.


Output:

Printing values in console using employee1 bean
Name 		: Ravi Raj
Designation 	: Technical Lead


Printing values in console using employee2 bean
Name 		: Ravi Raj
Designation 	: Technical Lead
employee1 hash Code : 6085929
employee2 hash Code : 6085929
Is Singleton Bean employee1 and singleton employee2 are same ? true


prototype Scope :

If the scope is set to prototype, spring container creates new instance of bean for each and every request for that bean. In spring bean dependency, prototype scoped bean is served by creating new instance of bean for each and every bean dependency. prototype scope is used for stateful beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown in the following code snippet.

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

Prototype Example:

For prototype example, let’s keep everything same as singleton scope example except some attribute in the Spring configuration file.In Spring configuration file Change the scope attribute to scope="prototype". Apart from that everything is same. Now its time to view output in the console.

Modify SpringContext.xml file as shown below.


Spring-Context.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" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.0.xsd">

	<bean id="employee" class="com.jwt.spring.Employee" scope="prototype">
	</bean>

</beans>

Output:

Printing values in console using employee1 bean
Name 		: Ravi Raj
Designation 	: Technical Lead


Printing values in console using employee2 bean
Name 		: null
Designation 	: null
employee1 hash Code : 1827969289
employee2 hash Code : 778786241
Is Singleton Bean employee1 and singleton employee2 are same ? false

Output in the console shows that, when second time bean is requested it returned a new instance instead of the old instance as in the case of singleton scope. And prints 'null' for member variables name/designation for the employee2 bean.

Also yot can see ferom above output,hashCode of both the instances are different and == operator returns false as well which confirms that both beans are different.


request Scope :

In spring, request scoped bean is used in HTTP request life-cycle. For each and every HTTP request, new instance of bean is created and is alive for complete HTTP request life-cycle. request scoped bean cannot be used with spring standalone application, it can be used only in web application.

In one HTTP request, only one instance of request scoped bean is created and in other subsequent request another instance of bean is created per request. The life cycle of request scoped bean starts and ends within the life cycle of HTTP request. Within HTTP request, the changes done in request scoped bean does not affect the other HTTP request. Once HTTP request is completed, the instance of request scoped bean is also destroyed.


session Scope :

session scoped bean in spring is used in HTTP Session of web application. For each and every HTTP session, only one instance of bean is created and is alive for complete HTTP session life cycle. The life cycle of session scoped bean is within the life cycle of HTTP session life cycle. If HTTP session is discarded, the session scoped bean created within HTTP session is also discarded.

Similar to request scope, it is applicable only for web aware spring application contexts.


globalSession Scope :

globalSession scoped bean is used in portlet based spring web application. Only one instance of globalSession scoped bean is created for life cycle of global HTTP session. Global HTTP session is the HTTP session that is shared among all portlets to make a single portlet web application. globalSession scoped bean instance has the life cycle within global HTTP session life cycle.


application Scope :

application scope has been introduced in Spring 4.0. Only one instance of bean is created for the complete life cycle of ServletContext. The instance of application scoped bean is stored as ServletContext attribute. application scoped bean is used in spring web application.

This scope is similar to singleton scope with one difference that application scope is ServletContext specific and singleton scope is spring ApplicationContext specific.

You can download the source code of the example by clicking on the Download link below.




comments powered by Disqus