Spring Bean Scope | 5 Major Types of Scope in Spring

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

1. Objective

In the previous article, we learned about the Spring Bean definition. Today, we will get to know about the Spring Bean Scope. Moreover, we will discuss different types of Scopes in Spring Beans. Each of the scopes will be defined with working examples using Eclipse IDE. In addition, we will get to know when to use a singleton and prototype scope in Spring Framework.
So, let’s start Spring Bean Scope.

Spring Bean Scope | 5 Major Types of Scope in Spring

Spring Bean Scope | 5 Major Types of Scope in Spring

2. Spring Bean Scope

As you know the scope of the Spring bean defines the life cycle and the visibility of the bean in contexts in which it is used. While defining a <bean> you have the chance of declaring the scope of that particular Spring bean.
Let’s explore Advantages of Spring Framework With Limitations

3. Types of Scope in Spring Bean

The Spring Framework has five types of scope that it supports. These are as follow:

a. Singleton Scope in Spring

If the Spring Bean scope is made singleton then the Spring IoC container defines only one instance of the object. That instance gets stored in the cache of singleton beans. Also, all the requests for that name will return the same instance which is cached. Along with that, any modifications made to that instance will get reflected in all references to a Spring bean.
Let’s create an entity Person as follow:

public class Person {
      private String name;
      // standard constructor, getters and setters
}

Spring Beans with singleton scope:

@Bean
@Scope("singleton")
public Person personSingleton() {
      return new Person();
}

Do you know the latest Job Roles and Salary trend of Spring Framework
You can also see two objects referring to same beans with same values:

private static final String NAME = "Sam";
@Test
public void givenSingletonScope_whenSetName_thenEqualNames() {
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
      Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
      Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
      personSingletonA.setName(NAME);
      Assert.assertEquals(NAME, personSingletonB.getName());
      ((AbstractApplicationContext) applicationContext).close();
}

The scopes.xml is as follows:

<?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="personSingleton" class="org.example.scopes.Person" scope="singleton"/>
</beans>

b. Prototype Scope in Spring

This will scope a bean definition to have any number of objects instances. It will return different instance every time request comes from IoC container.
Read about Spring Java Based Configuration – How to Configure Spring Beans
The prototype is set to the @Scope annotation in bean definition:

@Bean
@Scope("prototype")
public Person personPrototype() {
      return new Person();
}

You will see the same test which is done for the Spring Singleton scope which is two objects requesting same bean name:

private static final String NAME = "Sam";
private static final String NAME_OTHER = "Hari";
@Test
public void givenPrototypeScope_whenSetNames_thenDifferentNames() {
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
      Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
      Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
      personPrototypeA.setName(NAME);
      personPrototypeB.setName(NAME_OTHER);   
      Assert.assertEquals(NAME, personPrototypeA.getName());
      Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
      ((AbstractApplicationContext) applicationContext).close();
}

The scopes.xml is defined as:

<bean id="personPrototype" class="org.example.scopes.Person" scope="prototype"/>

c. Request Scope in Spring

This request will scope a bean definition to HTPP request. This is only there in context of web-aware Spring Application context. You will define the bean with the request scope under the @Scope annotation:

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestMessage() {
      return new HelloMessageGenerator();
}

The attribute proxyMode is needed as during the instantiation of web application context, there is no active request. The Spring Framework will create the proxy for the injection as a dependency.
Next, you should define the controller that has a reference to the requestMessage bean. For that, you need to access the same request more than once to test the web-specific scopes.

@Controller
public class ScopesController {
      @Resource(name = "requestMessage")
      HelloMessageGenerator requestMessage;
      @RequestMapping("/scopes")
      public String getScopes(Model model) {
       requestMessage.setMessage("Good morning!");
       model.addAttribute("requestMessage", requestMessage.getMessage());
       return "scopesExample";
      }
}

d. Session Scope in Spring

In the same way, you can define the beans within the session scope as:

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionMessage() {
      return new HelloMessageGenerator();
}

In the same fashion, the controller with the reference to the sessionMessage bean is defined. For that, you need to run two requests so as to show the value of message field is same for the session.
Have a look Spring Transaction Management – Types and Methods

@Controller
public class ScopesController {
     @Resource(name = "sessionMessage")
     HelloMessageGenerator sessionMessage;
     @RequestMapping("/scopes")
     public String getScopes(Model model) {
     sessionMessage.setMessage("Hello there!");
     model.addAttribute("sessionMessage", sessionMessage.getMessage());
     return "scopesExample";
      }
}

e. Global Session Scope in Spring

This scopes the bean definition to global HTTP session and is only valid for web-aware Application context of Spring. This type is used in portlet container applications where each portlet having their session. Now you will see the bean with globalSession scope under the @Scope annotation:

@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator globalSessionMessage() {
return new HelloMessageGenerator();
}

So, this was all about Spring Bean Scope Tutorial. Hope you like our explanation.

4. Conclusion

Hence, in this session, we have seen what is Spring Bean Scope and how to define the scopes of beans. In addition, we discussed different types of scopes in Spring Bean. Also, we saw each of the types of scopes defined separately with the examples using Eclipse IDE. Furthermore, if you have any query regarding Spring Bean Scope, feel free to ask in the comment section.
Related Topic- Integration of MVC with Spring
For reference

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *