In this article, you will learn about Spring Bean Scopes using @Scope annotation and XML configurations. If you are new to Spring, make sure you understand Dependency Injection in Spring.

Creating a bean means, you create the actual instance of the class with the dependencies injected based on the bean definition. Bean definition is like a recipe, you can create many instances of the class using the same recipe. Scope controls the number of instances that need to be created and the bean’s lifecycle.

Spring Framework supports six scopes and additionally, you can also create a custom scope.

  1. Singleton scope – @Scope("singleton") – The default scope for beans.
  2. Prototype scope – @Scope("prototype") – You get a new object instance of the class each time.
  3. Request scope – @RequestScope – An object instance is created for each single Http request.
  4. Session scope – @SessionScope – Scopes the single bean definition to the lifecycle of an Http Session. Valid for web-aware ApplicationContext.
  5. Application scope – @ApplicationScope – Scopes a single bean definition to the lifecycle of a ServletContext, only valid for web-aware ApplicationContext.
  6. WebSocket scope – @Scope("websocket") – Scopes the single bean definition to the lifecycle of a WebSocket. This is only valid for web-aware ApplicationContext.
  7. Custom scope – Spring also allows you to create a custom scoped bean.

1. The Singleton bean scope – @Scope(“singleton”)

When you define a bean as Singleton scoped, the Spring IoC creates exactly one instance of the object as per the bean definition. This single instance is stored in a cache, spring IoC returns this stored instance for all subsequent requests and references for the same bean.

In simple language, let’s say I declare itemDao as a singleton bean. No matter how many places I try to get this DAO bean, Spring will create only a single instance of this bean and inject the same everywhere I use.

Remember: Singleton is the default bean scope in Spring IoC.

There are of course several ways in which a bean scope can be declared. We will make use of the @Scope annotation.

Define the ItemDao bean with Singleton scope.

BasicIocConfig.java
@Configuration
public class BasicIocConfig {

  @Bean
  @Scope("singleton")
  public ItemDao itemDao() {
    return new ItemDao();
  }
}

You can also rewrite the @Scope as below

Java
  @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
  @Bean
  public ItemDao itemDao() {
    return new ItemDao();
  }

You can use the @Scope annotation with @Component, @Repository or @Service annotations.

ItemDao.java
@Scope("singleton")
@Component
public class ItemDao {
  public void doSomething(){ //... }
}

In XML Configuration, you can set the scope as below.

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="itemDao" scope="singleton" class="basic.ioc.demo.ItemDao"/>

</beans>

2. The Prototype bean scope – @Scope(“prototype”)

This scope is just the opposite of the Singleton. Spring IoC creates a new bean every time you request for a bean.

NOTE: You should always use prototype for all stateful beans like pojo, command objects, model objects etc.
And use singleton scope for stateless beans like DAO, Services, Controllers etc.

Just like singleton, prototype scope also can be defined as below.

BasicIocConfig.java
@Configuration
public class BasicIocConfig {

  @Bean
  @Scope("prototype")
  public Item item() {
    return new Item();
  }
}

Use the below approach to optimize string pool and avoid typos.

Java
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Alternatively, use the below approach if you are using XML configuration.

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="item" scope="prototype" class="basic.ioc.constructor.xml.Item"/>

</beans>

3. The Request scope spring bean – @RequestScope

The request, session, application and websocket scopes are available in Spring web-aware ApplicationContext. In simple language, these scopes are only available in Spring web application. Make sure you have done proper web-app/web MVC configuration before using them.

The request scope creates a new bean instance for each and every Http request.

Similar to the other scopes, if you are using the java configuration with annotations, use RequestScope annotation.

Java
@RequestScope
@Component
public class LoginRequestAction {
    // ...
}

Similarly, if you are using pure XML configuration

XML
<bean id="loginRequestAction" class="com.something.LoginRequestAction" scope="request"/>

4. The Session scope bean – @SessionScope

In a session scoped bean, spring Ioc creates one instance of the bean for the entire Http Session. Data like user preferences, shopping cart, etc makes sense to configure as session scoped.

ShoppingCart.java
@SessionScope
@Component
public class ShoppingCart {
    // ...
}

Similarly, if you are using XML configuration

XML
<bean id="shoppingCart" class="com.shopping.ShoppingCart" scope="session"/>

5. The Application Scope bean – @ApplicationScope

Application scoped beans are scoped at ServletContext level and stored as a regular ServletContext attribute. Application scope bean may sound like Singleton scoped bean, but are different in 2 important ways.

  1. Application scoped beans are singleton per ServletContext, not per ApplicationContext.
  2. It is exposed and visible as ServletContext attributes.

The configuration can be done using annotations or XML based as shown below,

AppThemePreferences.java
@ApplicationScope
@Component
public class AppThemePreferences {
    // ...
}

...
// For XML
<bean id="appThemePreferences" class="com.global.AppThemePreferences" scope="application"/>

6. The WebSocket scope bean – @Scope(“websocket”)

WebSocket-scoped beans are stored in the WebSocket session attributes. The same instance of the bean is then returned whenever it is referred during the entire WebSocket session.

UpdateNotifier.java
@Scope("websocket")
@Component
public class UpdateNotifier {
 //do tasks
}

I have demonstrated spring bean scopes with examples above. Mostly we will be using the prototype and singleton scopes in our applications. You can also refer to the official guide on Bean scopes.

By |Last Updated: April 1st, 2024|Categories: Spring Framework|

Table of Contents