Spring - Bean Scope

Spring - Bean Scope

Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides the flexibility to choose the required bean scope.

Types of Bean Scope

There are five types of bean scope available in Spring, from which three out of five scopes are available only if we use the Web-Application. The request, session, and global session are the scopes used with the web-app.

Scope Description
Singleton  It scopes a single bean definition into a single object instance per Spring IoC Container. It is the default scope type.
Prototype  It scopes a single bean definition into any number of object instances (required amount).
Request Itscopes a single bean definition to the lifecycle of a single HTTP request. It is used only with the web-aware applications.
Session Itscopes a single bean definition to the lifecycle of an HTTP session. It is used only with the web-aware applications.
global session Itscopes a single bean definition to the lifecycle of a global HTTP session. It is used only with the web-aware applications.
  1. The singleton scope

When we define a bean using the singleton scope, only one shared bean instance is created. All the requests to that bean will return a shared reference to that same bean. It is the default bean scope. If there is no bean scope defined in the bean-config file, the IoC container will treat it as a singleton scope. It can be used in a standalone Spring application and also cached in the memory.

Following code shows how to use a singleton bean scope:

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
      scope = "singleton">
 </bean> 

OR

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
 </bean> 

Example of Singleton Bean Scope

Coach.java

public interface Coach {
             public String training();
 } 

VolleyBall_Coach.java

public class VolleyBall_Coach implements Coach {
             public String training() {
                         return "10 rounds of the ground daily";
             }
 } 

applicationContext.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"  
         xmlns:p = "http://www.springframework.org/schema/p"  
         xsi:schemaLocation = "http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 <!--Define the dependency  -->
 <bean id = "mycoach" class ="com.app.Bean_Scopes.VolleyBall_Coach" scope ="singleton" > 
 </bean>
 </beans> 

App.java

import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
     public static void main( String[] args )
     {
                 ClassPathXmlApplicationContext appcon = new ClassPathXmlApplicationContext("applicationContext.xml"); 
         Coach coach = appcon.getBean("mycoach", Coach.class);
         Coach myCoach = appcon.getBean("mycoach", Coach.class);
         //check if these are the same beans
         Boolean rslt = (coach == myCoach);
         System.out.println("Pointing to the same object:" +"  " + rslt);
         // shows the memory location of the objects
         System.out.println("location of coach : " + coach); 
         System.out.println("location of coach : " + myCoach);
     }
 } 

Output

applicationContext.xml
  • The prototype scope

When we set the bean scope to prototype, a new instance of the object is created every time a request is made.As a predefined rule, the prototype scope is used for all stateful beans, whereas a singleton scope is used for all stateless beans. The prototype scope can also be used in a standalone application.

Following code shows how to use a prototype bean scope:

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
      scope = "prototype">
 </bean> 

Example of Prototype Bean Scope

Coach.java

public interface Coach {
             public String training();
 } 

VolleyBall_Coach.java

public class VolleyBall_Coach implements Coach {
             public String training() {
                         return "10 rounds of the ground daily";
             }
 } 

applicationContext.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"  
         xmlns:p = "http://www.springframework.org/schema/p"  
         xsi:schemaLocation = "http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 <!--Define the dependency  -->
 <bean id = "mycoach" class ="com.app.Bean_Scopes.VolleyBall_Coach" scope ="prototype" > 
 </bean>
 </beans> 

App.java

import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class App 
 {
     public static void main( String[] args )
     {
         ApplicationContext appcon = new ClassPathXmlApplicationContext("applicationContext.xml");
         Coach coach = appcon.getBean("mycoach", Coach.class); 
         Coach myCoach = appcon.getBean("mycoach", Coach.class);
         //check if these are the same beans
         Boolean rslt = (coach == myCoach);
         System.out.println("Pointing to the same object:" +"  " + rslt);
         // shows the memory location of the objects
         System.out.println("location of coach : " + coach);
         System.out.println("location of coach : " + myCoach); 
     }
 } 

Output

VolleyBall_Coach.java
  • The request scope

The request bean scope is used with the web-aware applications. When we set the bean scope to request, a new instance is created for each HTTP request.

Following code shows how to use a request bean scope:

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
      scope = "request">
 </bean> 
  • The session scope

The session bean scope is used with web-aware applications. When we set the bean scope to a session, a new instance is created for each HTTP request. When the HTTP session is terminated, the bean scoped with that session is also terminated.

Following code shows how to use a session bean scope:

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
      scope = "session">
 </bean> 
  • The global session scope

The global session bean scope is used with portal-based web applications. When we set the bean scope to a global session, a new instance is created for each HTTP request. It is similar to the session scope.

Following code shows how to use a global session bean scope:

<!—Defining the Scope in the bean -->
 <bean 
      id = "…" 
      class = "…" 
      scope = "globalSession">
 </bean> 


Related Topics

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring AOP – @AfterReturning Advice

Spring AOP – @AfterReturning Advice We have discussed earlier the types of advices available in Spring AOP. One of them is After Returning advice. It is an advice that executes after the normal execution...

3 minutes read.

Spring - Bean Scope

Spring - Bean Scope Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides...

6 minutes read.

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring MVC – @RequestParam

We have already discussed an example of Spring MVC in our previous tutorials. Here, we are going to discuss the @RequestParam annotation. In the last case, we had created a bean class for...

8 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on...

12 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the...

13 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.