06 - Spring Bean Scopes

6.1 Overview of Spring Bean Scopes

Spring framework supports five type of scopes and for bean instantiation and we can create a custom scope as well.

  • singleton- This is the default scope of the bean in Spring and it means that container will create a single instance per Spring IoC container.
  • prototype-  This scope allows the bean to be instantiated whenever it is requested which means multiple instance of a bean can be available.
  • request-  Spring bean configured as request scope instantiates the bean for a single HTTP request. Since HTTP requests are available only in web applications this scope is valid only for web-aware spring application context.
  • session Spring Beans configured as session scope lives through the HTTP session. Similar to request scope, it is applicable only for web aware spring application contexts.
  • global_session- This scope is equal to the  session scope on portlet applications. This scope is also applicable only for web aware spring application contexts. If this is global_session is used in normal web application (not in portlet), then it will behave as session scope and there will not be any error.

6.2 Define Spring Bean Scopes

We can define a scope of bean

    a) In bean definition itself using scope attribute of bean tag       

        <bean id="bean_id" class=”class_name” scope=" ">

     b) In Annotation based configuration we can use @Scope annotation on bean.

6.3 Spring Singleton Scope

As mentioned in overview section that container will create a single instance per Spring IoC container. Here the word “per Spring IoC container” is very important . This means that if a bean is defined in multiple configuration files , then each configuration file will instantiate a bean.

Singleton Scope is the default scope so if Spring beans so the beans without scope attribute or with value ‘session’ (scope=” singleton”) will be of scope session.

Stateless beans should be declared as singleton.

Below two statements are equivalent   

<bean id="singletonBean" class="SingletonBean"/>
<bean id="singletonBean" scope="singleton" class="SingletonBean"/>  

6.3.1 Spring Singleton Scope Example  

Create a java project and add the spring libraries as described in chapter 4.

6.3.1.1 Example to demonstrate the spring singleton scope 

Solution-

a) Define a bean (SingletonBean)

public class SingletonBean {
        private String message;
    public void setMessage(String message){
        this.message  = message;
    } 
    public String  getMessage(){
        return this.message;
    }
}                   

b) Create a beans.xml file in src directory to define the SingletonBean

<?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="singletonBean" scope="singleton" class="SingletonBean" />

</beans>

c) Create TestSingletonBean class which will just loads the beans.xml and test the singleton scope

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

public class TestSingletonBean {
      public static void main(String[] args) {

         ApplicationContext context = 
         new ClassPathXmlApplicationContext("beans.xml");

         SingletonBean singletonBeanA = (SingletonBean)context.getBean("singletonBean");
        
         System.out.println(singletonBeanA);
        
         SingletonBean singletonBeanB = (SingletonBean)context.getBean("singletonBean");

         System.out.println(singletonBeanB);

         System.out.println("Is Singleton Bean A and singleton B are same ? " +
         (singletonBeanA==singletonBeanB));
        
       }
}            
  1. Run the Program

You will see below output. HashCode of both the instances are same and == operator returns true as well which confirms that both beans are same.

Example program output

6.3.1.2  Example to demonstrate the spring “single instance per Spring IoC container” concept.

Solution-

a. Create a another-beans.xml file in src directory to define the SingletonBean.

<?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="singletonBean" scope="singleton" class="SingletonBean" />

</beans>

b. Update TestSingletonBean class which will just loads the SingletonBean class from beans.xml  and another-beans.xml

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

public class TestSingletonBean {
public static void main(String[] args) {
    ApplicationContext contextA = 
    new ClassPathXmlApplicationContext("beans.xml");

    ApplicationContext contextB = 
       new ClassPathXmlApplicationContext("another-beans.xml");

    SingletonBean singletonBeanA = (SingletonBean)contextA.getBean("singletonBean");
        
    System.out.println(singletonBeanA);
        
    SingletonBean singletonBeanB = (SingletonBean)contextB.getBean("singletonBean");

    System.out.println(singletonBeanB);
        
    System.out.println("Is Singleton Bean A and singleton B are same ? " +
    (singletonBeanA==singletonBeanB));

    }
}

c. Run the Program

You will see below output. HashCode of both instances are different  and == operator returns false which confirms that both beans are different.

Example program output

6.4 Spring Prototype Scope

Whenever  a bean configured with prototype scope is requested , container creates a new instance of bean. Stateful beans which hold the conversational state should be declared as prototype

To create a bean in prototype scope, use scope=”prototype”  or singleton=”false”

Below two statements are same

<bean id="prototypeBean" scope="prototype" class="PrototypeBean"/>
<bean id="prototypeBean" singleton="false" class="PrototypeBean"/>

6.4.1 Spring Prototype Scope Example 

Create a java project and add the spring libraries as described in chapter 4.

6.4.1.1  Example to demonstrate the Spring prototype scope

Solution-

a. Define a bean (PrototypeBean)

public class PrototypeBean {
   private String message;

   public PrototypeBean()
    {
        System.out.println("Prototype Bean Instantiated !!");
    }
    public void setMessage(String message){
        this.message  = message;
    }
    public String  getMessage(){
        return this.message;
    }
} 

b. Create a beans.xml file in src directory to define the PrototypeBean

<?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="prototypeBean" scope="prototype" class="PrototypeBean" />
</beans>

c. Create TestPrototypeBean class which will just loads the beans.xml and test the prototype scope

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

public class TestPrototypeBean {
       public static void main(String[] args) {
    
      ApplicationContext context = 
      new ClassPathXmlApplicationContext("beans.xml");

      PrototypeBean prototypeBeanA = (PrototypeBean)context.getBean("prototypeBean");
        
      System.out.println(prototypeBeanA);

      PrototypeBean prototypeBeanB = (PrototypeBean)context.getBean("prototypeBean");
        
      System.out.println(prototypeBeanB);
        
      System.out.println("Is Prototype Bean A and Prototype B are same ? " +
          (prototypeBeanA==prototypeBeanB));
   
    }
} 

d. Run the Program

          You will see below output. HashCode of both the instances are different  and == operator returns false as well which confirms that both beans are different. Also message added in constructor is displayed twice.

Output of Example program

Like us on Facebook