Monday 17 August 2015

Singleton or Default - Bean Scope

Singleton: This bean scope is default and it enforces the container to have only one instance per spring container irrespective of how much time you request for its instance.

This singleton behaviour is maintained by bean factory itself.


<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-2.5.xsd">
       <bean id="employee" class="spring.bean.scope.singleton.Employee" />
</beans>

package spring.bean.scope.singleton;
public class Employee {
       private String name;

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }
}

package spring.bean.scope.singleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSingleton {
       public static void main( String[] args )  {
              ApplicationContext context = new ClassPathXmlApplicationContext(
              new String[] {"spring/bean/scope/singleton/Spring-Customer.xml"});

              Employee custA = context.getBean("employee", Employee.class);
              custA.setName("Black shadow");
              System.out.println("Name : " + custA.getName());

              //retrieve it again
              Employee custB = context.getBean("employee", Employee.class);
              custA.setName("White shadow");
              System.out.println("Name : " + custB.getName());
             
              if(custA == custB) {
                     System.out.println("both are same instance : singleton");
              }
       }
}
Output:
Name: Black shadow
Name: White shadow
both are same instance


Is Singleton beans thread safe in Spring Framework?
Spring framework does not do anything under the hood concerning the multi-threaded behavior of a singleton bean.
It is the developer’s responsibility to deal with concurrency issue and thread safety of the singleton bean.
While practically, most spring beans have no mutable state (e.g. Service and DAO clases), and as such are trivially thread safe.
But if your bean has mutable state (e.g. View Model Objects), so you need to ensure thread safety.

The most easy and obvious solution for this problem is to change bean scope of mutable beans from “singleton” to “prototype“.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...