Tuesday, June 11, 2024

Bean Scopes in Spring With Examples

In this post we'll see different bean scopes provided by the Spring framework.

When you create a bean definition, you provide a configuration for creating actual instances of the class defined by that bean definition. By providing bean definition you can control not only, the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition.


Spring Bean Scope Description

Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports six bean scopes.

  1. singleton- Scopes a single bean definition to a single object instance per Spring IoC container. This is the default scope in Spring which means if you don't provide any scope Spring will consider the bean to have singleton scope.
  2. prototype- Prototype scope for a bean results in the creation of a new bean instance every time a request for that specific bean is made.
  3. request- Scopes a single bean definition to the life cycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  4. session- Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. application- Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  6. websocket- Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

Singleton Scope in Spring

If you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. 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 object.

The singleton scope is the default bean scope in Spring. To define a bean as a singleton in XML, you would write, for example:

<bean id="accountService" class="com.foo.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/>
If you want to define bean scope using annotation then you can use @Scope annotation along with the required scope.
@Service
@Scope("singleton")
public class DefaultAccountService{
 ...
 ...
}

Prototype scope in Spring

When you define a bean and provide prototype scope that results in the creation of a new bean instance every time a request for that specific bean is made.

Following example defines a bean with scope as prototype in XML:

<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
Using @Scope annotation same thing can be written as-
@Component
@Scope("prototype")
public class DefaultAccountService {
 ...
 ...
}

Note that Spring does not manage the complete life cycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization life cycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

Request scope in Spring

If a bean is defined with scope as request, it means Spring container creates a new instance of that bean by using the bean definition for each and every HTTP request.

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

When using annotation-driven components or Java configuration, the @RequestScope annotation (available from Spring 4) can be used to assign a component to the request scope or @Scope(WebApplicationContext.SCOPE_REQUEST).

@RequestScope
@Component
public class AccountLogin {
 ...
 ...
}

When the request completes processing, the bean that is scoped to the request is discarded.

Session Scope in Spring

If a bean is defined with scope as session the Spring container creates a new instance of the that bean by using the bean definition for the lifetime of a single HTTP Session. So the created bean instance is effectively scoped at the HTTP Session level.

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
When using annotation-driven components or Java configuration, you can use the @SessionScope annotation (available from Spring 4) to assign a component to the session scope or @Scope(WebApplicationContext.SCOPE_SESSION).
@SessionScope
@Component
public class UserPreferences {
  ...
  ...
}

When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.

Application scope in Spring

If a bean is defined with the scope as application, then the Spring container creates a new instance of the bean by using that bean's definition once for the entire web application.

<bean id="appPreferences" class="com.foo.AppPreferences" scope="application"/>
When using annotation-driven components or Java configuration, you can use the @ApplicationScope annotation (available from Spring 4) to assign a component to the application scope or @Scope(WebApplicationContext.SCOPE_APPLICATION).
@ApplicationScope
@Component
public class AppPreferences {
  ...
  ...
}

The bean is scoped at the ServletContext level, stored as a regular ServletContext attribute.

WebSocket scope in Spring

The Spring Framework provides a WebSocket API that you can use to write client- and server-side applications that handle WebSocket messages. You can declare a Spring-managed bean in the websocket scope. Those are typically singletons and live longer than any individual WebSocket session.

<bean id="appPreferences" class="com.foo.AppPreferences" scope="websocket"/>
Using @Scope annotation same thing can be written as-
@Component
@Scope("websocket")
public class MyBean {
  ...
  ...
}

Note that the request, session, application, and websocket scopes are available only if you use a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext, you get an IllegalStateException complaining about an unknown bean scope.

That's all for this topic Bean Scopes in Spring With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Dependency Injection in Spring Framework
  2. Bean Definition Inheritance in Spring
  3. How to Inject Prototype Scoped Bean in Singleton Bean
  4. Spring MessageSource Internationalization (i18n) Support
  5. @Required Annotation in Spring Framework

You may also like-

  1. Spring Java Configuration Example Using @Configuration
  2. Injecting Inner Bean in Spring
  3. Configuring DataSource in Spring Framework
  4. Dependency Injection Using factory-method in Spring
  5. Count Number of Words in a String Java Program
  6. @FunctionalInterface Annotation in Java
  7. How to Sort an ArrayList in Descending Order in Java
  8. Polymorphism in Java

No comments:

Post a Comment