Spring Bean Scopes Example

In this tutorial we will begin covering scope of Spring beans. In Spring when you define a bean in the Spring configuration file, you are telling Spring about its scope whether you define it or not. This is a powerful and flexible approach because you can choose the scope of the objects you create via configuration instead of having to hardcode the scope of an object at the Java class level. In Spring, when the scope of the bean is not explicitly defined it will default to a Singleton. The Spring framework supports the following five bean scopes. Three out of five are supported only in the context of web-aware Spring ApplicationContext.

In this post we will only cover Singleton and Prototype scope in detail although we will briefly mention the other three as well. These three will be covered in a subsequent post.

bean scope

Bean Scopes

TypeContextDescription
Singleton Singleton scope is the default bean scope. This bean scope is very similar to the Singleton Design Pattern used in Java. If the scope is not defined or is set to singleton, the Spring IoC container will create one instance of the object. This scope is the preferred scope for stateless beans.
Prototype Defining a bean as Prototype allows any number of object instances. When prototype scope is set, the Spring IoC container will create a new class instance every time a request the bean is made. This is a the preferred scope stateful beans.
RequestWeb-AwareWith this scope, each HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a Web-Aware Spring ApplicationContext.
SessionWeb-AwareThis scope is a little bit broader than the previous. With this scope, each session will have its own instance of a bean created. Only valid in the context of a Web-Aware Spring ApplicationContext.
Global SessionWeb-AwareThis scope is a bit broader than the Session and is really only applicable in portlet context. With this scope, each global HTTP session will have its own instance of a bean created.Only valid in the context of a Web-Aware Spring ApplicationContext.

Actor Class (Actor.java)

package com.avaldes;

public class Actor {
  private String name;
  private int age;
  private String height;
  
  public String getName() {
    return name;
  }
  
  public void setName(String name) {
    this.name = name;
  }
  
  public int getAge() {
    return age;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  public String getHeight() {
    return height;
  }
  
  public void setHeight(String height) {
    this.height = height;
  }
  
  @Override
  public String toString() {
    return "Actor [name=" + name + ", age=" + age + ", height=" + height + "]";
  }
}

The Singleton Scope

As mentioned earlier Singleton beans, are created only one by the IoC container. The container will then reuse the same instance of the bean whenever it is referred again. Singleton beans are the default because the designers felt that in practice most services, controllers and resources that are configured in the container are implemented as thread-safe classes and do not carry any state past their initialization. The following image comes from the Spring Source documentation and provides an excellent reference for what happens in the container.

Singleton Pattern
Image Courtesy: Spring Source

The Prototype Scope

When prototype scope is used the Spring IoC container will create a new class instance every time a request the bean is made. Every time the bean is referenced or injected into another bean will result in a new bean being instantiated. The following image comes from the Spring Source documentation and provides an excellent reference for what happens in the container.

prototype pattern
Image Courtesy: Spring Source

Testing Singleton vs Prototype Bean Scopes (TestBeanScopeExample.java)

In this example, we two types of beans, a singletonActor and a prototypeActor. In the first example, we see the effect of having singleton scope, because we only set the the instance for actor1 instance. We then create another instance called actor2 and use the getBean() method but we do not set any of the the values in this instance. When we print out the details of actor1 and actor2 we can see that they are actually referring to the same instance as the IoC container will only create one instance per container. However, when we use prototype scope, the IoC container will create a unique instance every time we use the getBean() method or every time the bean is referenced and injected into another bean in the spring-context.xml. In order to compare and contrast the two different beans, we define a prototype-scoped bean and create two instances using the names actor3 and actor4. we will do as we did previously, we set one of the actors directly, in the case, we set actor3 to Hugh Jackman while leaving actor4 untouched. When we print out the details of actor3 and actor4 we can see that they are actually referring to different and unique instances.

package com.avaldes;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBeanScopeExample {

  public static void main(String[] args) {
    BeanFactory beanFactory = 
                new ClassPathXmlApplicationContext("spring-config.xml");
    
    System.out.println("----Spring Singleton Bean-----");
    Actor actor1 = (Actor) beanFactory.getBean("singletonActor");
    actor1.setName("Jennifer Lawrence");
    actor1.setAge(24);
    actor1.setHeight("5' 11\"");
    System.out.println("Actor1 Singleton: " + actor1.toString());
    
    Actor actor2 = (Actor) beanFactory.getBean("singletonActor");
    System.out.println("Actor2 Singleton: " + actor2.toString());
    
    System.out.println("\n----Spring Prototype Bean-----");
    Actor actor3 = (Actor) beanFactory.getBean("prototypeActor");
    actor3.setName("Hugh Jackman");
    actor3.setAge(46);
    actor3.setHeight("6' 2\"");
    System.out.println("Actor3 Prototype: " + actor3.toString());
    
    Actor actor4 = (Actor) beanFactory.getBean("prototypeActor");
    System.out.println("Actor4 Prototype: " + actor4.toString());    
  }
}

spring-config.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.xsd">
 
  <bean id="singletonActor" class="com.avaldes.Actor" scope="singleton">
  </bean>
  
  <bean id="prototypeActor" class="com.avaldes.Actor" scope="prototype">
  </bean>
</beans>

Output – Singleton vs Prototype Bean Scope

Take a look at the completed object, and notice you the children, phones and favoriteNumbers are constructed and how the output looks.

----Spring Singleton Bean-----
Actor1 Singleton: Actor [name=Jennifer Lawrence, age=24, height=5' 11"]
Actor2 Singleton: Actor [name=Jennifer Lawrence, age=24, height=5' 11"]

----Spring Prototype Bean-----
Actor3 Prototype: Actor [name=Hugh Jackman, age=46, height=6' 2"]
Actor4 Prototype: Actor [name=null, age=0, height=null]

spring framework

Related Posts

  • Introduction to Spring Framework, IoC and Injection
    In this tutorial we will cover a basic introduction the Spring framework, Inversion of Control and Dependency Injection. We will discuss the benefits of using it, and why it is so popular in today's environment.
  • Spring Framework Constructor Injection Example
    In this tutorial, we will concentrate on Constructor Injection. As the name suggests, constructor injection is form of dependency injection that is accomplished when we supply the arguments to the constructor so that when the bean is instantiated by the factory it contains all of the necessary information to be property constructed.
  • Spring Framework Constructor Injection with Collections Example
    In this tutorial, we will modify our previous example and add a few collections so we can illustrate how we use constructor injection with differing collection types. Specifically, we will show how to perform constructor injection with List, Map and Set objects.
  • Spring Framework Setter Injection with Examples
    In this tutorial we will discuss Spring Framework Setter Injection which is the main method of dependency injection in Spring. The property element is used to define the setter injection in Spring by using the name of the property element and looking for the corresponding setXXXXXX methods in the specified bean.
  • Spring Bean Scopes Example
    In this tutorial we will begin covering scope of Spring beans. In Spring when you define a bean in the Spring configuration file, you are telling Spring about its scope whether you define it or not. This is a powerful and flexible approach because you can choose the scope of the objects you create via configuration instead of having to hardcode the scope of an object at the Java class level.
  • Spring Bean Life Cycle Example – @PostConstruct, @PreDestroy, InitializingBean, DisposableBean, init-method and destroy-method
    In this tutorial we will cover the Spring Bean Life Cycle and the methods, attributes and annotations used to hook into the management of the bean life cycle in the IoC container.
  • Integrating Java JMX Managed Beans using Spring and Annotations
    This post will show how to create managed beans using the JMX standard using Spring. JMX stands for Java Management Extensions, and was created to implement a standard and uniform way to manage your applications. By using JMX remote can connection to a JVM and monitor running applications on that JVM. In addition to monitoring, remote clients are able to directly run methods and modify runtime parameters of the application that is being managed.
  • Integrating Spring Message Driven POJO with ActiveMQ
    This post will show how to create a message driven POJO that can send and receive JMS message using ActiveMQ as the Message Oriented Middleware (MOM). We will discuss various approaches to creating the MDPs (Message Driven POJOs) in this tutorial and discuss setting up ActiveMQ from Apache.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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