What are Bean Scopes ?

In the spring bean configurations, bean attribute called ‘scope’ defines what kind of object has to created and returned

<bean id = “” class = “” scope = “”></bean>

When you create a bean definition what you are actually creating is an actual instance of the class defined by that bean definition.

So you can control object creation using scope attribute. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to the scope of an object at the Java class level.

Spring Framework supports five scopes

Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition for any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request that is each and every 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.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

The singleton scope

  • Singleton scope is the default one.
  • Singleton scope should be used for stateless beans.
  • When a bean is a singleton, only one shared an 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.
  • 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.

Singleton Example

<!– by default singleton -->
<bean id=“service" class="com.foo.TestService"/>

<!– using spring-beans-2.0.dtd -->
<bean id=“service" class="com.foo.TestService" scope="singleton"/>

<!– backward compatibility in spring-beans.dtd -->
<bean id=“service" class="com.foo.TestService" singleton=“true”/>

The prototype scope

  • Prototype scope for all beans that are stateful.
  • Prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made.
  • Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance.
  • This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called.
  • It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources used by prototype-scoped beans is through the use of a custom bean post-processor which would hold a reference to the beans that need to be cleaned up.

Prototype Example

<!– using spring-beans-2.0.dtd -->
<bean id=“service" class="com.foo.TestService" scope=“prototype"/>

<!– backward compatibility in spring-beans.dtd -->
<bean id=“service" class="com.foo.TestService" singleton=“false”/>

Other Scope

The other scopes, namely request, session, and global session are for use only in web-based applications.

If you are using a web-aware Spring ApplicationContext implementation (such as XmlWebApplicationContext). If you try using these next scopes with regular Spring IoC containers such as the XmlBeanFactory or ClassPathXmlApplicationContext, you will get an IllegalStateException complaining about an unknown bean scope.

Other Scopes Examples

  • Request – Spring container will create a brand new instance of the LoginAction bean using the ‘loginAction’ bean definition for each and every HTTP request. When the request is finished processing, the bean that is scoped to the request will be discarded.
  • Session – Spring container will create a brand new instance of the UserPreferences bean using the ‘userPreferences’ bean definition for the lifetime of a single HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session will also be discarded.
  • Global Session – The global session scope is similar to the standard HTTP Session scope, and really only makes sense in the context of portlet-based web applications.

Spring Singleton v/s Singleton Design Pattern

  • Spring singleton is described as “per container per bean”. Or Singleton scope in spring means the single instance in a spring context.
  • Singleton pattern says that one and only one instance of a particular class will ever be created per class loader.
  • Spring singleton bean can be any normal class you write, but declaring it’s scope as singleton means that Spring will only create one instance and provide its reference to all beans that reference the declared bean. You may have many instances of that class in your application, but only one will be created for that bean. You may even have multiple beans of the same class all declared as the singleton. Each bean will create exactly one instance of the class.
  • A Java singleton, per the design pattern where instantiation is restricted to one, usually per JVM class loader by the code.

Lets Implement

Project structure be like below image

1

add the dependency in pom.xml file –

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.4.RELEASE</version>
</dependency>

bean class “Greetings.java

package com.spring.core;
public class Greetings {
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

beans.xml configuration be like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <!-- By default "Singleton" -->
    <bean id="greet1" class="com.spring.core.Greetings">  
        <property name="message" value="Hello One"></property>
    </bean>
    <bean id="greet2" class="com.spring.core.Greetings">  
        <property name="message" value="Hello One"></property>
    </bean>
    <!-- you can change to "Prototype" also -->
    <!-- <bean id="greet" class="com.spring.core.Greetings" scope="prototype">  
        <property name="message" value="Hello One"></property>
    </bean> -->
</beans>

Application main class

package com.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Greetings greet = (Greetings) context.getBean("greet1");  
        System.out.println(greet+" : "+greet.getMessage());  
        Greetings greet1 = (Greetings) context.getBean("greet2"); 
        System.out.println(greet1+" : "+greet1.getMessage());
    }
}

Output –

Dec 28, 2016 12:59:29 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@300ffa5d: startup date [Wed Dec 28 12:59:29 IST 2016]; root of context hierarchy
Dec 28, 2016 12:59:29 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
com.spring.core.Greetings@3fee9989 : Hello One
com.spring.core.Greetings@73ad2d6 : Hello One

For more detail, Please watch below video –

 

Thanks for reading 🙂

Please Subscribe our you tube channel Almighty Java

Leave a comment