ApplicationContext axt = new ClassPathXmlApplicationContext("Singleton.xml");
TestSingleton testSingleton1 = (TestSingleton) axt.getBean("Singleton1");
TestSingleton testSingleton2 = (TestSingleton) axt.getBean("Singleton2");
System.out.println(testSingleton1.toString());
System.out.println(testSingleton2.toString());
Singleton.xml
<!--这里的scope不论我加不加都是无效的-->
<bean id="Singleton1" class="spring.test.TestSingleton" scope="singleton"></bean>
<bean id="Singleton2" class="spring.test.TestSingleton" scope="singleton"></bean>
output
spring.test.TestSingleton@3df78040
spring.test.TestSingleton@44050988
------ Solution ------------------------------------ --------
you do not call a single case of this model, a single case of a bean should be configured in applicationContext (the only one ) , then the object is a singleton getBean
---- - Solution --------------------------------------------
Singleton1
Singleton2
singleton object is to create only one oh
------ Solution ---------------------------- ----------------
in the spring where the bean is set to single cases
object should be generated when the front access backstage only one
------ Solution ------------------------- -------------------
personally feel singleton pattern is a bean is only one instance of the object , that is, no matter how many times you axt.getBean ("Singleton1" ) is a bean instance , but you this is two bean, each of which is to get an instantiated , it will be different .
xml
<-! here whether I added without scope is invalid - >
Java code
ApplicationContext axt = new ClassPathXmlApplicationContext ("Singleton.xml");
TestSingleton testSingleton1 = (TestSingleton) axt.getBean ("Singleton1");
TestSingleton testSingleton2 = (TestSingleton) axt.getBean ("Singleton1");
System.out.println (testSingleton1.toString ());
System.out.println (testSingleton2.toString ());
on the
------ Solution --------------------------------- -----------
inject your configuration file is different singleton, if so write axt.getBean ("singleton") inside the same singleton can be verified , print out the memory address line .
------ For reference only -------------------------------------- -
spring management BEAN, in which the configuration file , do not own the new .
------ For reference only -------------------------------------- -
------ For reference only ---------------------------------- -----
landlord did not pay attention to the sentence: " the current context ." Can be understood as the same thread context. Two configurations, two different thread context is , of course, two different instances. Further , even with a configuration in different contexts will be instantiated to different entities.
没有评论:
发表评论