is an object in the spring container in the end a number of cases or a single case?
The default is a singleton, when the scope is set to prototype, when the object is created with multiple instances, when it is a multi-instance, regardless of lazy-init why value, are all in Context.getbean (); When you create an object
1.applicationcontext.xml
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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 "> <BeanID= "HelloWorld"class= "Com.spring.scope.HelloWord"></Bean> <BeanID= "HelloWorld2"class= "Com.spring.scope.HelloWord"Scope= "Prototype"></Bean> </Beans>
2. Test code
Helloword
Package Com.spring.scope; Public class Helloword { public Helloword () { System.out.println ("Create Object"); } publicvoid hello () { System.out.println ("Hello word!" ); }}
3. Testing
Packagecom.spring.scope.test;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportCom.spring.scope.HelloWord; Public classHellowordtest {/*** * objects in the Spring container, by default are singleton * Because the object is a single column, so long as a property is declared on a class that contains data, then this property will be global (dangerous)*/@Test Public voidTestscope_default () {//start the spring containerApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); //extract the beans from the spring container according to the IDHelloword Helloword = (Helloword) context.getbean ("HelloWorld"); Helloword HelloWord2= (Helloword) context.getbean ("HelloWorld"); System.out.println (Helloword); System.out.println (HELLOWORD2); //Create Object//[email protected]//[email protected] } /*** * If the scope for the Prototype,spring container is a multi-instance * * * If an object is a multi-instance, this object will change when created in the spring container, then the object will not be created when it is started, then GETBE An () creates an object * i.e.: * If scope is prototype, the object is created at Context.getbean () regardless of the value of Lazy-init. * */@Test Public voidTestscope_prototype () {//start the spring containerApplicationContext context=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); //extract the beans from the spring container according to the IDHelloword Helloword = (Helloword) context.getbean ("HelloWorld2"); Helloword HelloWord2= (Helloword) context.getbean ("HelloWorld2"); System.out.println (Helloword); System.out.println (HELLOWORD2); /*Create object Create object [email protected] [email protected]*/ } }
Multi-instance and single-instance of a Springioc_ object