Sunday, February 9, 2014


Singleton beans in Spring and classes based on Singleton design pattern are quite different.
The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it. In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept. So, in summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.
Here is some example:
spring-config.xml
   
   
       
   
Bean A
 public class A{  
   private String text;  
   public String getText() {  
     return text;  
   }  
   public void setText(String text) {  
     this.text = text;  
   }  
 }  
Test
 public class Test {  
   public static void main(String[] args) {  
     ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");  
     A a1 = ctx.getBean("a", A.class);  
     a1.setText("text A1");  
     A a2 = ctx.getBean("a", A.class);  
     a2.setText("text A2");  
     System.out.println("a1: " + a1.getText());  
     System.out.println("a2: " + a2.getText());  
   }  
 }  
Output:
 a1: text A2  
 a2: text A2  
And now let's create another one ApplicationContext:
 public class Test {  
   public static void main(String[] args) {  
     ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");  
     ApplicationContext ctx2 = new ClassPathXmlApplicationContext("spring-config.xml");  
     A a1 = ctx.getBean("a", A.class);  
     a1.setText("text A1");  
     A a2 = ctx2.getBean("a", A.class);  
     a2.setText("text A2");  
     System.out.println("a1: " + a1.getText());  
     System.out.println("a2: " + a2.getText());  
     // both ctx and ctx2 have same classloaders  
     System.out.println("context1 classloader: " + ctx.getClassLoader());  
     System.out.println("context2 classloader: " + ctx2.getClassLoader());  
   }  
 }  
Output:
 a1: text A1  
 a2: text A2  
 context1 classloader: sun.misc.Launcher$AppClassLoader@5284e9  
 context2 classloader: sun.misc.Launcher$AppClassLoader@5284e9  


Links:
stackoverflow.com
java-sample-program.blogspot.in

No comments: