I am have a test class and I have defined it in my spring bean config file as below:
<bean id = "springsingleton1" class = "com.learn.stackoverflow.general.SpringSingleton"/>
<bean id = "springsingleton2" class = "com.learn.stackoverflow.general.SpringSingleton" scope="prototype"/>
<bean id = "springsingleton3" class = "com.learn.stackoverflow.general.SpringSingleton"/>
My expectation was that this will throw some exception because firstly I have defined a singleton bean and then I am trying to create another prototype of the same, or if exception is not thrown then I will always get the same instance for all 3 cases but I am getting different instance. Below is code:
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("C:\\E_Drive\\Projects\\Workspace\\Test\\CS101\\src\\com\\learn\\stackoverflow\\general\\bean.xml");
SpringSingleton springSingleton11 = (SpringSingleton) applicationContext.getBean("springsingleton1");
SpringSingleton springSingleton21 = (SpringSingleton) applicationContext.getBean("springsingleton2");
SpringSingleton springSingleton22 = (SpringSingleton) applicationContext.getBean("springsingleton2");
SpringSingleton springSingleton3 = (SpringSingleton) applicationContext.getBean("springsingleton3");
SpringSingleton springSingleton12 = (SpringSingleton) applicationContext.getBean("springsingleton1");
System.out.println("springSingleton11 : " + springSingleton11.hashCode());
System.out.println("springSingleton21 : " + springSingleton21.hashCode());
System.out.println("springSingleton22 : " + springSingleton22.hashCode());
System.out.println("springSingleton3 : " + springSingleton3.hashCode());
System.out.println("springSingleton12 : " + springSingleton12.hashCode());
Output:
springSingleton11 : 1658926803
springSingleton21 : 210652080
springSingleton22 : 1652149987
springSingleton3 : 1107730949
springSingleton12 : 1658926803
How I am getting more than one instance, doesn't Spring enforces singleton?
Please note that I have read this question and it doesn't answer my doubts.