Scope:
Singleton: singleton, Only one instance is created throughout the application (default)
prototype: prototype, Create a new instance each time you inject
session: sessions, Creating one instance per session
request: requests, Each request creates an instance
By default , beans are singleton, initialized at the following time, invoking the constructor of each bean
1 <BeanID= "person"class= "com.guigu.spring.autowire.Person"2 P:name= "Tom" ></Bean>3 //equivalent to:4 <BeanID= "person"class= "com.guigu.spring.autowire.Person"5 P:name= "Tom"Scope= "singleton"></Bean>
1 New Classpathxmlapplicationcontext ("scope.xml"); Here initialize, call the Bean's constructor 2person person1 = (person) ctx.getbean (' person '3 Person person2 = (person) ctx.getbean (' person '4 system.out.println (person1 = = person2); Result: true
In the first row, the constructor is called, the object is instantiated, and there is only one object. Person1 and Person2 are actually the same object.
If the prototype :
1 < id= "person" class= "com.guigu.spring.autowire.Person"2 p:name= "Tom" scope= "prototype"></Bean >
similarly, two calls, The result will be false
1 New Classpathxmlapplicationcontext ("scope.xml"); // initialized here, But no instance is created at this time 2 Person Person1 = (person) Ctx.getbean (' person '3person person2 = (person) Ctx.getbean (' person ') c11>4 system.out.println (person1 = = person2); // result: false
Prototype specifies that when the container is initialized, the instance is not created automatically, but instead is created when it is Called. Two calls were made, and two instances were created.
session: The same bean is the same as the one in the sessions, and the different session is different bean
Request: Generate a new bean for each HTTP request
Spring Learning record (v)---bean scope scope