Spring Bean Scopes

Spring Bean Scopes

In this post, we will cover different bean scopes in Spring Framework. We will cover different Spring Bean Scopes with their use case.

 

Introduction

Bean definition in Spring is to create a recipe for creating the actual instance of the class defined in the Bean.Spring Framework provides different scopes to create an object based on the bean definition.Spring out of the box supports following 7 Bean Scopes:

  • singleton
  • prototype
  • request
  • session
  • application
  • websocket
  • globalSession

 

1. The singleton scope

Spring Bean defined with singleton scope will have only one instance. To put it in a simple term, Spring Ioc container will create exactly one instance for that object. Spring container will always return the same instance. Spring Framework use store all singleton bean in the cache and all request and references for that bean will be returned from the cache. The singleton scope is the default scope in Spring.

Let’s create an Order entity to understand it more clearly

public class OrderService {
    
    @Bean
    @Scope("singleton")
    public OrderService getOrder(){
        return new OrderService();
    }

}

You can use ConfigurableBeanFactory to define scope using a constant value than String.

@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)

To define bean as singleton in 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 
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
<bean id="orderService" class="com.javadevjournal.demo.service.OrderService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="orderService" class="com.javadevjournal.demo.service.OrderService" scope="singleton"/>
</beans>

 

2. The prototype scope

Singleton bean is suitable for stateless beans. Spring container will create a new instance of prototype bean every time we make a request for this bean. For example, if we are injecting this bean into another bean, it will create a new instance of this prototype bean every time a request made to the parent bean. Prototype scope is best suitable for stateful beans.

public class OrderService {
       
    @Bean
    @Scope("prototype")
    public OrderService getOrder(){
        return new OrderService();
    }

}

There are few interesting things about prototype scope.

  • Spring container does not manage the complete life-cycle of these beans.
  • IoC container creates prototype bean and hands over this to the client, it is the responsibility of the client to manage this bean.
  • Spring container take care of cleaning up resources in case bean is no longer in use, for prototype scope, configured destruction life-cycle callbacks are not called.
  • The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
  • Always use custom bean post processor to perform cleanup work (recommended).

Rest of the bean scopes,

  • request scope
  • session scope,
  • application scope,
  • websocket scope

are only available in the web-aware application. They need minor configurations before we can define and use these scopes in our application. 

  • For Spring Web MVC application all these scopes are available and exposed by DispactherServlet and it requires no additional setup.

 

If you are not using Spring’s DispactherServlet, you need to configure org.springframework.web.context.request.RequestContextListener in your application. you can use a web.xml or Spring WebApplicationInitializer for Servlet 3.0+.

 

3. The request scope

Spring container will create a new instance of request scope bean for each and every HTTP request.

public class AddToCart {

    @Bean
    @RequestScope
    public AddToCart getCart(){
        return  new AddToCart();
    }
}

XML configuration for request scope bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.AddToCart" scope="request"/>
</beans>

AddToCart instance is scoped at the request level.

  • We can change AddTOcart instance to any level as other instance created for this scope will not have any information on the changes done to this AddTocart instance.
  • Spring container will discard this bean once the request completes processing.

 

4. The session scope

Spring container will create a new instance of the session scope bean for the life-cycle of a single HTTP session.This works similar to request scope beans in terms of the visibility of the bean internal status to other bean created in different HTTP session.

public class AddToCart {

    @Bean
    @SessionScope
    public AddToCart getCart(){
        return  new AddToCart();
    }
}

XML configuration for session scoped bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.AddToCart" scope="session"/>
</beans>

 

5. The application scope

Spring container creates only one bean definition for the entire web application. 

public class SystemConfiguration {

    @Bean
    @ApplicationScope
    public SystemConfiguration getConfig(){
        return  new SystemConfiguration();
    }
}

XML configuration for application scoped bean

<?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.xsd">
    
<bean id="addToCart" class="com.javadevjournal.demo.SystemConfiguration" scope="application"/>
</beans>

 

6. The WebSocket scope

The WebSocket scope is new scope in the Spring Framework.

@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class WebSocketBean {

    //Web Socket Bean
}

Spring IoC container creates a new bean instance per WebSocket Session

 

7. The GlobalSession scope

The globalSession scope is more connected to the Portlet environment.Bean created under globalSession scope will be available for all portlet. This scope work similar to session scope beans under servlet environment.

public class GlobalSessionBean {

    @Bean
    @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public  GlobalSessionBean getGlobalSession(){
        return new GlobalSessionBean();
    }
}

[pullquote align=”normal”]As of Spring 3.0, a thread scope is available which is not register by default and need to be registered like any other custom scope bean. Read for more detail. [/pullquote]

 

Summary

In this post, we discussed different Spring Bean Scopes and what their intended usages are. It is always good to clearly understand the different bean scopes. 

Comments are closed.