Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Spring Bean scope


May 14, 2021 Spring


Table of contents


The scope of the bean

When you define a bean in Spring, you must declare the options for the scope of the bean. F or example, in order to force Spring to produce a new bean instance each time you need it, you should declare the scope of the bean's property to prototype. Similarly, if you want Spring to return the same bean instance every time you need it, you should declare the bean's scope property singleton.

The Spring framework supports the following five scopes: singleton, prototype, request, session, and global session, as shown below.

Note that if you use web-aware ApplicationContext, three of them are available.

Scope Describe
singleton

There is only one bean instance in the spring IoC container, and the bean exists as a single case, the default

prototype Each time a bean is called from a container, a new instance is returned, i.e. each time getBean() is called, the equivalent of performing a newXxxBean()
request Each HTTP request creates a new bean, which applies only to WebApplicationContext environments
session The same HTTP Session shares a bean, which is used differently by Session and is only available in WebApplicityContext environments
global-session Typically used in Portlet application environments, this scope applies only to WebApplicityContext environments

The first two scopes will be discussed in this chapter, and the remaining three will be discussed when we will discuss web-aware Spring ApplicationContext.

Singleton scope:

Singleton is the default scope, that is, when a bean is defined, the scope of the bean is defaulted to singleton if no scope configuration item is specified.

When a bean's scope is Singleton, only one shared bean instance exists in the Spring IoC container, and all requests to the bean, as long as the id matches the bean definition, return only the same instance of the bean.

That is, when a bean definition is set to singleton scope, the Spring IoC container creates only a unique instance of that bean definition.

Singleton is a single-case type that automatically creates a bean object at the same time when the container is created, whether you use it or not, and he exists, each time the object is acquired is the same object. N ote that the Singleton scope is the default scope in Spring. You can set the scope property to singleton in the bean's profile, as follows:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
</bean>

Example

We use the Eclipse IDE in the right place, and then follow these steps to create a Spring application:

Steps Describe
1 Create a project named SpringExample, and create a package com.tutorialspoint in the src folder that created the project.
2 Use the Add External JARs option to add the Spring library you want, explained in the Spring Hello World Example section.
3 Create Java-like HelloWorld and MainApp in the com.tutorialspoint package.
4 Create the Beans profile Beans file in the src .xml.
5 The final step is to create the contents of all Java files and bean profiles and run the application as explained below.

Here is the contents .java HelloWorld file:

package com.tutorialspoint;
public class HelloWorld {
   private String message;
   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Here's what .java MainApp files are:

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
      objA.setMessage("I'm object A");
      objA.getMessage();
      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

Here's the profile beans that are required for the singleton scope.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-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" 
      scope="singleton">
   </bean>

</beans>

Once you've created the source code and bean profile, we're ready to run the application. If everything is fine with your application, the following information will be output:

Your Message : I'm object A
Your Message : I'm object A

Prototype scope

When the scope of a bean is Prototype, it represents a bean definition that corresponds to multiple object instances. T he bean of the Prototype scope causes a new bean instance to be created each time the bean request is requested (injecting it into another bean, or calling the container's getBean() method as a program. P rototype is a prototype type that is not instantiated when we create a container, but creates an object when we get a bean, and we don't get the same object every time we get it. As a rule of law, prototype scopes should be used for stately beans, and singleton scopes should be used for stateless beans.

To define the prototype scope, you can set the scope property to prototype in the bean's profile, as follows:

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="prototype">
   <!-- collaborators and configuration for this bean go here -->
</bean>

Example

We use the Eclipse IDE in the right place, and then follow these steps to create a Spring application:

Steps Describe
1 Create a project named SpringExample, and create a package com.tutorialspoint in the src folder that created the project.
2 Use the Add External JARs option to add the Spring library you want, as explained in the Spring Hello World Example section.
3 Create Java-like HelloWorld and MainApp in the com.tutorialspoint package.
4 Create the Beans profile Beans file in the src .xml.
5 The final step is to create the contents of all Java files and bean profiles and run the application as explained below.

Here is the contents .java HelloWorld file:

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Here's what .java mainApp files are:

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
      objA.setMessage("I'm object A");
      objA.getMessage();
      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

Here are the profile Beans files that are required for the prototype scope.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-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" 
      scope="prototype">
   </bean>

</beans>

Once you've created the source code and bean profile, we're ready to run the application. If everything is fine with your application, the following information will be output:

Your Message : I'm object A
Your Message : null