Friday, 25 August 2017

Spring Bean Scopes: Singleton, Prototype, Request, Session, and Application

        The core of the Spring Framework is the BeanFactory, which is responsible for creating and managing beans within the Spring container. A bean's scope defines the lifecycle of the bean and determines how many instances of the bean are created and managed by the container.

Spring provides five built-in bean scopes. Two of them are available in all Spring applications, while the remaining three are available only in web-aware ApplicationContext implementations. 

The five bean scopes are singleton, prototype, request, session, and application (previously referred to as global session in older versions of Spring).


Spring Bean Scopes
Spring Bean Scopes

  • singleton

With the singleton bean scope, the Spring IoC container creates only one instance of the bean per container, regardless of how many times it is requested. This is the default bean scope in Spring. The Spring container manages and maintains this single instance throughout the application's lifecycle.

Example: EmployeeService.java
package com.adnblog.employee;

public class EmployeeService { 
 
     String message;

     public String getMessage() {
           return message;
     }

     public void setMessage(String message) {
          this.message = message;
     }
}  

Spring bean configuration file : spring-employee.xml (if scope is not declared, default it should be singleton)

<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-2.5.xsd">

       <bean id="employeeService"
            class="com.adnblog.employee.EmployeeService" />

</beans>

Spring code - Main Program
 
package com.adnblog;

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

import com.adnblog.employee.EmployeeService;

public class MainClass { 
 
       public static void main( String[] args ) { 
 
              ApplicationContext context =
                               new ClassPathXmlApplicationContext(new String[] {"spring-employee.xml"});

              EmployeeService empService = (EmployeeService)context.getBean("employeeService");
              empService.setMessage("empService Message");
              System.out.println("Message : " + empService.getMessage());

              //trying to create second instance
             EmployeeService empService1 = (EmployeeService)context.getBean("employeeService");
             System.out.println("Message : " + empService1.getMessage());
      }
}

Output Message : empService Message
                Message : empService Message


  • prototype

     With the prototype bean scope, the Spring IoC container creates a new instance of the bean each time it is requested. Unlike the singleton scope, a new object is created for every request.

To use the prototype scope, set the bean's scope to prototype in the bean configuration, as shown below:


<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-2.5.xsd">

       <bean id="employeeService"
            class="com.adnblog.employee.EmployeeService"  scope="prototype"/>

</beans>

Run the main program, you will get output  

Output : Message : empService Message

               Message : null



  • request

       With the request bean scope, a new bean instance is created for each HTTP request made by the client. Once the request is completed, the bean goes out of scope and becomes eligible for garbage collection.

This scope is available only in a web-aware ApplicationContext, such as WebApplicationContext.

  • session

    The session bean scope is similar to the request scope, but it creates one bean instance per user session. The same bean instance is shared throughout the user's session. Once the session ends, the bean goes out of scope and becomes eligible for garbage collection.

This scope is available only in a web-aware ApplicationContext, such as WebApplicationContext.


  •  global-session

      The global session scope is specific to Portlet-based applications. In a Portlet container, an application consists of multiple portlets. Each portlet has its own session, but if you want to share a bean instance across all portlets within the same application, you can use the global session scope.

In Servlet-based applications, the global session scope has no special behavior and functions the same as the session scope. It is worth noting that the global session scope is primarily intended for Portlet environments and is rarely used in modern Spring Boot applications.


No comments:

Post a Comment