In Spring framework, we can create beans in 6 inbuilt spring bean scopes and you can also define your custom bean scope as well. Out of these six scopes, four are available only if you use a web-aware
ApplicationContext.
singleton and
prototype scopes are available in any type of IOC containers.
Table of Contents 1. Spring Bean Scope Types 1.1. singleton scope 1.2. prototype scope 1.3. request scope 1.4. session scope 1.5. application scope 1.6. websocket scope 2. Custom thread scope 3. Summary
1. Spring Bean Scopes Type
In Spring, scope can be defined using spring bean @Scope annotation. Let’s quickly list down all six inbuilt bean scopes available to use in spring application context. These same scope apply to spring boot bean scope as well.
1.1. singleton scope
singleton is default bean scope in spring container. It tells the container to create and manage only one instance of bean class, per container. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached instance.
Example of singleton scope bean using Java config –
@Component //This statement is redundant - singleton is default scope @Scope("singleton") //This statement is redundant public class BeanClass { }
Example of singleton scope bean using XML config –
<!-- To specify singleton scope is redundant --> <bean id="beanId" class="com.howtodoinjava.BeanClass" scope="singleton" /> //or <bean id="beanId" class="com.howtodoinjava.BeanClass" />
1.2. prototype scope
prototype scope results in the creation of a new bean instance every time a request for the bean is made by application code.
You should know that destruction bean lifecycle methods are not called
prototype scoped beans, only initialization callback methods are called. So as developer, you are responsible for clean up prototype-scoped bean instances and any resource there hold.
Java config example of prototype bean scope –
@Component @Scope("prototype") public class BeanClass { }
XML config example of prototype bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="prototype" />
prototypescope for all stateful beans and the
singletonscope for stateless beans.
RequestContextListeneror
RequestContextFilter.
1.3. request scope
In
request scope, container creates a new instance for each and every HTTP request. So, if server is currently handling 50 requests, then container can have at most 50 individual instances of bean class. Any state change to one instance, will not be visible to other instances. These instances are destructed as soon as the request is completed.
Java config example of request bean scope –
@Component @Scope("request") public class BeanClass { } //or @Component @RequestScope public class BeanClass { }
XML config example of request bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="request" />
Read More: How web servers work?
1.4. session scope
In
session scope, container creates a new instance for each and every HTTP session. So, if server has 20 active sessions, then container can have at most 20 individual instances of bean class. All HTTP requests within single session lifetime will have access to same single bean instance in that session scope.
Any state change to one instance, will not be visible to other instances. These instances are destructed as soon as the session is destroyed/end on server.
Java config example of session bean scope –
@Component @Scope("session") public class BeanClass { } //or @Component @SessionScope public class BeanClass { }
XML config example of session bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="session" />
1.5. application scope
In
application scope, container creates one instance per web application runtime. It is almost similar to
singleton scope, with only two differences i.e.
applicationscoped bean is singleton per
ServletContext, whereas
singletonscoped bean is singleton per
ApplicationContext. Please note that there can be multiple application contexts for single application.
applicationscoped bean is visible as a
ServletContextattribute.
Java config example of application bean scope –
@Component @Scope("application") public class BeanClass { } //or @Component @ApplicationScope public class BeanClass { }
XML config example of application bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="application" />
1.6. websocket scope
The WebSocket Protocol enables two-way communication between a client and a remote host that has opted-in to communication with client. WebSocket Protocol provides a single TCP connection for traffic in both directions. This is specially useful for multi-user applications with simultaneous editing and multi-user games.
In this type of web applications, HTTP is used only for the initial handshake. Server can respond with HTTP status 101 (switching protocols) if it agrees – to handshake request. If the handshake succeeds, the TCP socket remains open and both client and server can use it to send messages to each other.
Java config example of websocket bean scope –
@Component @Scope("websocket") public class BeanClass { }
XML config example of websocket bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="websocket" />
Please note that
websocket scoped beans are typically singletons and live longer than any individual WebSocket session.
2. Custom thread scope
Spring also provide a non-default
thread scope using class
SimpleThreadScope. To use this scope, you must use register it to container using
CustomScopeConfigurer class.
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer"> <property name="scopes"> <map> <entry key="thread"> <bean class="org.springframework.context.support.SimpleThreadScope"/> </entry> </map> </property> </bean>
Every request for a bean will return the same instance within the same thread.
Java config example of thread bean scope –
@Component @Scope("thread") public class BeanClass { }
XML config example of thread bean scope –
<bean id="beanId" class="com.howtodoinjava.BeanClass" scope="thread" />
3. Summary
Spring framework has provided six spring bean scopes and instances have different lifecycle span within each scope. As a developer, we must choose the scope of any container managed bean wisely. Also, we must take wise decisions when beans with different scopes refer each other.
Try to remember all above given information to answer any spring bean scope interview questions.
Happy Learning !!
Hi Lokesh,
Could you please explain details about when we use bean scope as “prototype”?
Use prototype when you want to create a new instance everytime. This is mostly done for the stateful beans (beans which have class fields that are shared with multiple instances of the class).
There are other scopes are also available like
application
websocket
Thread Scope
HI Lokesh,
Can you please explain how single bean(Singleton bean) used by different users. Ie how Spring manage session internally.
Hi Lokesh,
I encountered with this question in one of the interviews. What will happen if we give the dependency of a prototype scoped bean inside a singleton bean? It will be very helpful if you can give any real life example. Thanks in advance..
As singleton beans are created only once, so the instance of prototype scope bean will be created only once when singleton bean is created. This is NOT the desired behavior because prototype bean instance MUST be created everytime singleton bean instance is fetched from spring context.
To overcome this problem, we use lookup method injection. Read more on this SO Thread.
Hi Lokesh,
Can’t we use scoped proxy beans for this?
Thanks,
Prabhath
Can you suggest a use case for this ?
Having different instances of a bean inside a Singleton bean can create problems i think. Correct me if i am wrong. Is this a good practise ?
thank you for this post. I m really wondering about the spring bean scrope. Thank you really.
Hi Lokesh,
I am newly started Spring. I am using STS tool for spring project. When i started working with some core programming i am getting
“Caused by: java.io.FileNotFoundException: class path resource [src/main/java/net/core/example/app-context.xml] cannot be opened because it does not exist”
Error. I placed app_context.xml in class path , tried with several changes but still getting same error. Please help me .
If i used same code without using repository(adding only spring jars) it works better But with maven repository i am getting error.
Code :
ApplicationContext ac = new ClassPathXmlApplicationContext
(“/src/main/java/net/core/example/app-context.xml”);
Error log :
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [src/main/java/net/core/example/app-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [src/main/java/net/core/example/app-context.xml] cannot be opened because it does not exist)
verify what you have configured in web.xml. It will look something like this.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/employee-servlet.xml</param-value>
</context-param>
Hi Lokesh,
I am not using any web application example.i stated from core Spring written simple application. when i added maven dependency to application i got error.
hi lokesh,
scope examples plzz..one by one
I have written separate posts containing examples. Please find here.
Hi Lokesh,
Can you tell me some real life programming examples (in brief) where to use singleton and where to use prototype. for eg : in a flipkart application where we gonna use singleton and where prototype.
Thanks in Advance!
Worth reading.. Thanks for your time and efforts.