Different Spring Bean Scope

The 5 different Spring bean scopes you should know about

  • singleton (Core)
  • prototype (Core)
  • request (Web-aware)
  • session (Web-aware)
  • global session (Web-aware)

spring bean scopes

Singleton scope

This is the default scope. It means that you don’t set Scope for bean singleton it will be.

It means that the IoC container will only create exactly one instance of the object defined by that bean definition. The container stores this particular instance to a cache. Therefore all request which points to that bean will get this single instance. So it preserves our state among the requests.

singleton spring bean

Example for singleton bean definition in XML:

<bean id="customereService" class="com.injection_sample.CustomerServiceImpl"/>

<bean id="customereService" class="com.injection_sample.CustomerServiceImpl" scope="singleton"/>

<bean id="customereService" class="com.injection_sample.CustomerServiceImpl" singleton="true"/>

Example for singleton bean definition with Annotation:

@Configuration
@ComponentScan
public class AppConfig {
  
  @Bean(name= "customerService")
  @Scope("singleton")
  public CustomerService getCustomerServiceImp() 
  {
    return new CustomerServiceImp();
    
  }
  
  @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
  @Bean(name= "customerRepository")
  public CustomerRepository getCustomerRepositoryImp() 
  {
    return new CustomerRepositoryImp();
    
  }
}

Check how it works:

public class App 
{	
    public static void main( String[] args )
    {
    	ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    	
    	CustomerService service = context.getBean("customerService", CustomerService.class);  	
    	CustomerService service2 = context.getBean("customerService", CustomerService.class);
    	
        System.out.println(service);
        System.out.println(service2);
    }
}

Let’s look at the generated output:

[email protected]81071
[email protected]81071

Here we can see, that the service instances are the same.

Prototype scope

If you define a bean as a prototype the IoC container will server a new instance from that bean every time you call for it. Hence you will lose state made to that bean between the requests.

prototype scope bean

Example for Prototype bean definition in XML:

<bean id="customerService" class="com.zoltanraffai.inject_sample.CustomerServiceImp" scope="prototype"/>

<bean id="customerService" class="com.zoltanraffai.inject_sample.CustomerServiceImp" singleton="false"/>

Example for prototype bean definition through annotation:

@Configuration
@ComponentScan
public class AppConfig {
  
  @Bean(name= "customerService")
  @Scope("prototype")
  public CustomerService getCustomerServiceImp() 
  {
    return new CustomerServiceImp();
    
  }
  
  @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  @Bean(name= "customerRepository")
  public CustomerRepository getCustomerRepositoryImp() 
  {
    return new CustomerRepositoryImp();
    
  }
}

Here if run our application and check the messages we can notice that the result is different:

[email protected]b04f
[email protected]494d8

As you can see the instances that we got are not the same.

Web-Aware Scopes

As we mentioned at the start of this article there are 3 three scopes which are only available in the web-aware application context. These objects are created through an HTTP call. The DispatcherServlet in Spring receives the request and starts to search through the WebApplicationContext for the appropriate bean. The WebApplicationContext instantiates beans with the @Controller and @RequestMappingannotation. These annotations provide metadata to pair the requested URL with the appropriate Endpoint.

Hence, these Scopes specify that which bean instance will serve us for each HTTP call that we make.

The default Scope here is the Singleton scope as well.

Request scope

The web container creates a new instance for every independent HTTP request. Hence, they destroy every time when the call ends.

XML example:

<bean id="customerService" class="com.zoltanraffai.inject_sample.CustomerServiceImp" scope="request"/>

Annotation example:

@RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class HomeController {
  @RequestMapping("/")
  public String callService() {
    
    return this.toString();
    
  }	
}

If you start your web application and refresh your page you can check that the instance reference will be different every time.

Session scope

The container returns a new instance for every session. Hence if we call our controller in the same Session the result will be the same. You can try it simply by opening two independent browsers, each browser will show different instance reference, but if you refresh them they stay the same per browser.

XML example:

<bean id="customerService" class="com.zoltanraffai.inject_sample.CustomerServiceImp" scope="session"/>

Annotation example:

@RestController
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class HomeController {
  
  
  @RequestMapping("/")
  public String callService() {	
    return this.toString();	
  }
}

GlobalSession scope

The global session scoped bean instance is shared across your web application. Hence every call receives the same bean instance. Its similar to the singleton in normal core applications.

XML example:

<bean id="customerService" class="com.zoltanraffai.inject_sample.CustomerServiceImp" scope="globalSession"/>

Annotation example:

@RestController
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION)
public class HomeController {
  
  
  @RequestMapping("/")
  public String callService() {	
    return this.toString();	
  }
}

Therefore you check it easily with the multiple browser approaches. The same instance reference string will return for every call in different browsers.

Toufiq Mahmud