Spring 5 – Bean scopes

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.

ScopeDescription
singleton (default)Single bean object instance per spring IoC container
prototypeOpposite to singleton, it produces a new instance each and every time a bean is requested.
requestA single instance will be created and available during complete lifecycle of an HTTP request.

Only valid in web-aware Spring ApplicationContext.

sessionA single instance will be created and available during complete lifecycle of an HTTP Session.

Only valid in web-aware Spring ApplicationContext.

applicationA single instance will be created and available during complete lifecycle of ServletContext.

Only valid in web-aware Spring ApplicationContext.

websocketA single instance will be created and available during complete lifecycle of WebSocket.

Only valid in web-aware Spring ApplicationContext.

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" />
As a rule, you should prefer to use the prototype scope for all stateful beans and the singleton scope for stateless beans.
To use beans in the request, session, application and websocket scopes, you need to register the RequestContextListener or 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.

  1. application scoped bean is singleton per ServletContext, whereas singleton scoped bean is singleton per ApplicationContext. Please note that there can be multiple application contexts for single application.
  2. application scoped bean is visible as a ServletContext attribute.

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

16 thoughts on “Spring 5 – Bean scopes”

    • 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).

      Reply
  1. HI Lokesh,

    Can you please explain how single bean(Singleton bean) used by different users. Ie how Spring manage session internally.

    Reply
  2. 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..

    Reply
    • 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.

      Reply
      • 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 ?

        Reply
  3. 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
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

    Reply
    • 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>

      Reply
      • 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.

        Reply
  4. 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!

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.