Spring Bean Scopes

Spring framework has provided 6 spring bean scopes and instances have different lifecycle span within each scope

singleton the single bean definition to a single object instance per Spring IoC container.

prototype the single bean definition to any number of object instances inside the Spring IoC container.

Web Aware Scopes

request Creates a new bean definition per HTTP request; that is each and every HTTP request will have its own instance of a bean created. Only valid in the context of a web-aware Spring ApplicationContext.

session A new bean will be created for each HTTP session by the container.

application   The application scope creates the bean instance for the lifecycle of a ServletContext.

WebSocket session The request is made during the entire WebSocket session,the same instance of the bean is then returned.

1). Singleton

A single bean instance is created per Spring IOC. A single instance of bean returned for each time. All requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

 
public class Student {

	public Student() { 
		System.out.println("Student instance created...");
	}

}

 

XML configuration

 
<bean id="student" class="com.javacodestuffs.Student" />

 
<bean id="student" class="com.javacodestuffs.Student" scope="singleton" />

 
<bean id="student" class="com.javacodestuffs.Student" singleton="true" />
 

Annotation configuration

 
 	
	@Bean
	@Scope(value="singleton")
    public Student student() {
		return new Student();
	}
 
 

 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		 Student student1 = ctx.getBean(Student.class);
		 System.out.println(student1.hashCode());

		 Student student2 = ctx.getBean(Student.class);
		 System.out.println(student2.hashCode());

		ctx.close();
	}

}

 

Here we get the same hashcode for both the beans instance, indicates that there is only a single instance of a bean created inside the Spring IOC.

2). The prototype scope

In the prototype scope, a brand new bean is created per request to the spring container. In the above example, we have to make changes in the configuration file as,

XML configuration

<bean class="com.javacodestuffs.Student" id="student" scope="prototype" />
<bean class="com.javacodestuffs.Student" id="student" singleton="false" />

Annotation configuration

 
@Bean
@Scope(value="prototype")
public Student student() {
	return new Student();
}
 

 
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MySpringApp {

	public static void main(String[] args) {

		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MyConfiguration.class);
		ctx.refresh();

		 Student student1 = ctx.getBean(Student.class);
		 System.out.println(student1.hashCode());

		 Student student2 = ctx.getBean(Student.class);
		 System.out.println(student2.hashCode());

		ctx.close();
	}

}
  
   

The other scopes, namely

Request, Session, and Application session are for use only in
web-based applications.

3). Request scope

For each and every HTTP request new bean is created. n the following example, For every Http call to loginService , new bean created each time.

XML configuration

 
  
<bean class="com.javacodestuffs.LoginService" id="loginService" scope="request" />

 
   

Annotation configuration

    
 @Bean
@Scope(value="request")
public LoginService loginService() {
	return new LoginService();
}
   

4). Session Scope

Spring container will create a brand new instance of the Session Scoped bean for the lifetime of a single HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.

XML configuration

 
    <bean class="com.javacodestuffs.LoginService" id="loginService" scope="session" />
 


   

Annotation configuration

  
@Component
@Scope("session")
public class LoginService {
  
  
}
 
 

  
@Component
@SessionScope
public class LoginService {
}
  

5). Application scope

Spring container will create one instance per web application runtime. It is almost similar to the singleton scope, but have small differences.

application scoped bean is singleton per ServletContext, whereas singleton scoped bean is singleton per ApplicationContext. There can be multiple application contexts for a single spring application. application scoped bean is visible as a ServletContext attribute.

XML configuration

  

 <bean class="com.javacodestuffs.LoginService" id="loginService" scope="application" />
 
 

 
 

Annotation configuration

 
 @Component
@Scope("application")
public class LoginService {
}
 
 

  
@Component
@ApplicationScope
public class LoginService {
}


6). WebSocket scope

WebSocket Protocol provides a single TCP connection for traffic in both directions.

In the WebSocket scope, when the beans first accessed, they are stored in the WebSocket session attributes. Whenever the request is made during the entire WebSocket session, The same instance of the bean is then returned.

This type of scope used in multi-user applications with simultaneous editing and multi-user games.

XML configuration

  
 <bean class="com.javacodestuffs.LoginService" id="loginService" scope="websocket" />
 

 
   

Annotation configuration

    
@Component
@Scope("websocket")
public class LoginService {
}
  

Custom thread scope

Spring also provides a non-default thread scope using class SimpleThreadScope. To use this scope, you must use register it to the container using CustomScopeConfigurer class. Every request for a bean will return the same instance within the same thread.

   

<pre class="code-pre"><span style="font-size: 14px;"> <code class="codeblock">  
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="thread">
                <bean class="org.springframework.context.support.SimpleThreadScope">
            </bean></entry>
        </map>
    </property>
</bean>   
 
 

Here are some questions related to scopes of the beans in spring.

What is the default scope of bean in the spring framework?  
Singleton. This scope implies that Spring container will create an only shared instance of the class designated by this bean, so each time the Bean is required the same object will be injected.

When to use singleton and prototype scope in spring?

In your application, if the same object is returned each time, we need to use the singleton scope for that bean. 

The Prototype scope is preferred for the stateful beans, and the spring container does not manage the complete lifecycle of a prototype bean i.e. destruction lifecycle methods are uncalled. Like so, a developer is responsible for cleaning up the prototype-scoped bean instances and any resources it holds.

Why singleton is default scope in spring?
If you're not going to hold state data in beans then it's enough to have only one instance of each bean. You should also remember that it's not JVM singletons - just Spring singletons. So you don't have to provide only private constructors and any getInstance() methods.

 Its spring container manages for you, else in normal java, you have to do code for it. When a service bean is stateless, it's thread-safe, and it can scale to any number of concurrent requests.

In this article, we have seen different Spring Bean Scopes in Spring IOC Container.