Customizing Spring beans – scope

Spring beans can be created with multiple scopes. The default scope is a singleton.

A Singleton, in general, is a Java class with only one instance per JVM. In the context of the Spring Framework, a singleton is a class that has one instance per Spring application context.

Since there is only one instance of a singleton bean, it cannot contain any data that is specific to a request.

The scope can be provided with the @Scope annotation on any Spring bean:

    @Service 
@Scope("singleton")
public class BusinessServiceImpl implements BusinessService

The following table shows the different types of scopes available for beans:

Scope

Use

Singleton

By default, all beans are of the Singleton scope. Only one instance of such beans is used per instance of the Spring IoC container. Even if there are multiple references to a bean, it is created only once per container. The single instance is cached and used for all subsequent requests using this bean. It is important to specify that the Spring Singleton scope is one object per one Spring container. If you have multiple spring containers in a single JVM, then there can be multiple instances of the same bean. So, the Spring Singleton scope is a little different from the typical definition of a singleton.

Prototype

A new instance is created every time a bean is requested from the Spring container. If a bean contains a state, it is recommended that you use the prototype scope for it.

request

This is available only in Spring web contexts. A new instance of the bean is created for every HTTP request. The bean is discarded as soon as the request processing is done. It's ideal for beans that hold data specific to a single request.

session

This is available only in Spring web contexts. A new instance of the bean is created for every HTTP session. It's ideal for data specific to a single user, such as user permissions in a web application.

application

It's available only in Spring web contexts. One instance of a bean per web application. It's ideal for things such as application configuration for a specific environment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset