Spring Core

Spring Bean Scopes in IoC Container

In this article we will discuss about Spring bean scopes. In Spring application, we get the bean from the Spring container with some default configuration. Default behavior is that every beans in the Spring container are initialized when bean configuration file loaded to the JVM.  Whenever getBean is called container recognized the bean by given bean id and return that bean to the caller. One more default behavior is that every beans has only one instance in the spring container.

Spring Bean Scopes

Spring Bean Scopes means which is used to decide which type of bean instance should be return from Spring container back to the caller. Basic Spring Bean Scopes are only two types-

1. Singleton:(Default)

Scopes a single bean definition to a single object instance per Spring IoC container.

2. Prototype:

Scopes a single bean definition to any number of object instances.

But at web environment spring have three more scopes as following:

Request Scope:

This scopes a bean definition to an HTTP request.

Session Scope:

This scopes a bean definition to an HTTP session.

Global Session:

Scopes a single bean definition to the lifecycle of a global HTTP Session.

 

 

We 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. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration.

Basic Spring Bean Scopes are only two types are given below.
  1. Singleton Bean ScopeReturn a single bean instance per Spring IoC container
  2. Prototype Bean ScopeReturn a new bean instance each time when requested

1. Singleton Bean Scope:

Scopes a single bean definition to a single object instance per Spring IoC container. This is the default behavior of the spring container.

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

We can say another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

To define a singleton scope, you can set the scope property to singleton in the bean configuration file, as shown below:

<bean class="com.dineshonjava.sdnext.beanscope.Point" id="zeroPoint" scope="singleton">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

See the singleton scope of bean with full example.

Using Annotation for Bean Scope:
@Service
@Scope("singleton")
public class Point
{
   private int x;
   private int y;
   
   public void setX(int x){
      this.x = x;
   }

   public void setY(int y){
      this.y = y;
   }
}

See the singleton scope of bean with full example.
NOTE : This singleton is differ from the singleton pattern in Java Class. Single pattern in java mean you can create the only one instance of a that class in JVM. But In spring singleton bean scope means every container can create only single bean in the Spring IoC Container but a JVM can have multiple Spring IoC Container so JVM can multiple beans rather than bean singleton bean scope.

 

2. Prototype Bean Scope:

If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown below:

<bean class="com.dineshonjava.sdnext.beanscope.Point" id="zeroPoint" scope="prototype"><property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

See the full example of prototype bean scope with using the Annotation.

Using Annotation for Bean Scope:
@Service
@Scope("prototype")
public class Point
{
   private int x;
   private int y;
   
   public void setX(int x){
      this.x = x;
   }

   public void setY(int y){
      this.y = y;
   }
}

See the full example of prototype bean scope with using the Annotation.

 

There are three wen application aware bean scope are given below.

1. Request Scope:

This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="request"></bean>

2. Session Scope:

This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="session"></bean>

3. global-session:

This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="globalSession"></bean>
The global session scope is similar to the standard HTTP Session scope (described immediately above), and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session.

Please note that if you are writing a standard Servlet-based web application and you define one or more beans as having global session scope, the standard HTTP Session scope will be used, and no error will be raised.

Spring Related Topics you may like

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago