Close

Spring - Bean Scopes

[Last Updated: Mar 20, 2021]

Scope of a bean determines the life span of a bean instance per container. There are two core scopes



  1. singleton : There's only one instance of bean per Spring container (here container mean per org.springframework.context.ApplicationContext). That means regardless of how many times, we access/inject the bean there will be only one instance provided by the container. This is the default one. This is different than Java famous singleton design pattern in that there's one Spring singleton per spring container, whereas, there's one Java singleton per JVM level.
  2. prototype : A new instance of a bean is created, each time it's injected to some other bean or accessed via the container (springContext.getBean(...)).


  3. The singleton beans can be considered stateless (suitable for a service, DAO or controller etc) , whereas prototypes are stateful with respect to a particular calling session (for example shopping cart, wizard like steps etc).

    Why don't we create prototype beans ourselves using new operator rather than registering it to the Spring container? Yes we should if we can, but prototype can be used to have Spring to do some DI in it.

    The @Scope annotation

    There are two ways to use @Scope annotation to assign the scopes to beans.

    Using on bean factory methods of @Configuration class :

    @Scope is used in @Configuration annotated class's method. These methods should primarily be annotated with @Bean.


    Using on classes annotated with @Component:

    @Scope is used on component classes. This classes should be scanned by Spring at startup if @ComponentScan along with packages to scan is defined on @Configuration class.




    No Pre Destroy callback for Prototype

    Spring does not manage the complete lifecycle of a prototype bean. The container instantiates, configures, a prototype bean instance, and hands it to the client, with no further record of the instance. That's the reason, the prototype bean's method annotated with PreDestroy will never be called. The initialization lifecycle callback methods (@PostConstruct) are always called on all objects regardless of scope.

    Bean Scopes in Web Aware ApplicationContext

    Following are the three scopes available, if spring application loaded using WebApplicationContext

    1. request: One instance per HTTP request, i.e. every new HTTP request will have its own instance of the bean.
    2. session: One instance per HTTP session.
    3. globalSession: One instance per global HTTP session. Typically only valid when used in a portlet context.

    In next tutorials we will see the examples of Singleton and Prototype beans.

See Also