I understand that the bean lifecycle consists of two aspects: when the bean is created, when the bean is destroyed from the creation to the destruction of the execution flow one, bean creation and destruction
The timing of the creation of a bean is primarily determined by a number of configuration items, including the Scope property, which determines whether the bean is singleton (singleton) or multi-case (prototype), which defaults to Singleton Singleton; Lazy-init Property, Only valid for Singleton mode, decide whether to delay loading , the default is False, indicating that when the container is initialized, a singleton is generated, the requestmapping attribute, which is the annotation mvc, when there is this attribute, the Lazy-init property is invalidated (not a simple conflict, Instead, Requestmapping generates a singleton in another logical process; 1.scope Properties
There are two main enumerations, Singleton and prototype, and the default value is singleton. 1.1 Configure scope, if not configured, the default value is singleton XML configuration
<bean id= "Loginservice" class= "Com.springapp.mvc.service.impl.LoginServiceImpl" scope= "prototype"/>
annotation configuration, directly using @scope annotations
@Scope (Value=configurablebeanfactory.scope_prototype)
1.2 Enumeration MeaningsSingleton, which represents a singleton pattern, is well understood, indicating that only one instance of the bean exists in the container, and each time the bean is requested, the same is returned. Cases:
Example 1.2.1
@Component public class Person {public person
() {
System.out.println ("person initialization ...");
Public
static void Main (String args[]) {
beanfactory beanfactory = new Classpathxmlapplicationcontext (" Mvc-dispatcher-servlet.xml ");
SYSTEM.OUT.PRINTLN ("Container initialization Complete");
Person Person1 = (person) beanfactory.getbean ("person");
Person Person2 = (person) beanfactory.getbean ("person");
System.out.println (Person1.equals (Person2));//Same instance, print True
}
}
output: Person
initialization ...
Container initialization Complete
true
Prototype, which means a new bean instance is created each time the bean is requested, for example:
Example 1.2.1
//In the preceding example, add an annotation before the class:
@Scope (value = configurablebeanfactory.scope_prototype)
output:
container initialization complete Person
initialization ...
Person initialization ...
False
2.lazy-init Property
A Boolean enumeration that has a value of two true and false, and the default value is true. This configuration is only valid at Scope=singleton 2.1 configuration Lazy-init, the default value is True in the XML configuration
<bean id= "Loginservice" class= "Com.springapp.mvc.service.impl.LoginServiceImpl" lazy-init= "true"/>
annotation configuration, using @lazy annotations
Use @Lazy before the class
2.2 Enumeration MeaningsLazy-init=false, which means that when the container is initialized, a singleton bean is created, which is the default configuration, so in example 1.2.1, print "person initialization ..." before printing "container initialization complete" lazy-init=true, at the first Getbean, To create a bean, for example
Example 2.2.1
//adding annotations before the person class @lazy
output:
container initialization complete person
initialization
... True
3. Configure Nesting
Mainly refers to Singleton and prototype two different beans of the mutual reference, more specifically, is actually singleton to prototype reference. Because there are four ways to reference each other, there are three kinds of results very clear, namely: prototype or singleton reference Singleton, because Singleton in the container will only have one instance, so the result is definitely reference the same class; Prototype references prototype, re-created instances are again injected with new dependencies and will certainly be re-created.
So, only singleton to prototype reference, at first I understand the mistake, thought prototype each time will change, the following example:
//example 3.1 @Component @Scope (value = configurablebeanfactory.scope_prototype) public class Apple
{public Apple () {System.out.println ("Apple initialize ...");
}} @Component public class Person {@Resource Apple Apple;
Public person () {System.out.println ("person initialization ...");
} public void Eat () {System.out.println ("Apple hashcode=" +apple.hashcode ()); } public static void Main (String args[]) {beanfactory beanfactory = new Classpathxmlapplicationcontext ("Mvc-di
Spatcher-servlet.xml ");
SYSTEM.OUT.PRINTLN ("Container initialization complete");
Person Person1 = (person) beanfactory.getbean ("person");
Person Person2 = (person) beanfactory.getbean ("person");
Person1.eat ();
Person2.eat ();
}} Output: Person initialization ...
Apple Initialize ... Container initialization complete Apple hashcode=10745331 Apple hashcode=10745331
It was thought that every time the bean of the person was acquired, the Apple was re-injected, and the result was that the injection would only occur once when the bean was created, and when the subsequent Getbean was found, the singleton person would be present, and the instance would be returned directly, without re-injection.
But if there is a need to recreate the new Apple every time, how can it be implemented? On the Internet to check the information, you need to use the Lookup-method property configuration. 4 Lookup-method Properties
This property is used to get the prototype bean in the singleton Bean, and the new bean is recreated every time the call is made. 4.1 principle
The user specifies the method that the bean injects when it is injected, and then calls this method to get it using the bean. The spring container automatically replaces the method body with Cglib and dynamically calls Getbean to fetch the bean and return it. Look at the source code:
1. Parse the Lookup-method property and register//org.springframework.beans.factory.xml.beandefinitionparserdelegate#
Parselookupoverridesubelements/** * Parse lookup-override sub-elements of the given bean element. */public void parselookupoverridesubelements (Element beanele, Methodoverrides overrides) {NodeList NL = beanele.getc
Hildnodes ();
for (int i = 0; i < nl.getlength (); i++) {Node node = Nl.item (i); if (iscandidateelement (node) && nodenameequals (node, lookup_method_element)) {element ele = (Element)
Node
String methodName = Ele.getattribute (Name_attribute);
String beanref = Ele.getattribute (bean_element);
New Lookup Overloaded Object lookupoverride override = New Lookupoverride (MethodName, beanref);
Override.setsource (Extractsource (ele));
Register to the Bean definition in overrides.addoverride (override); }}}//2. Call the Lookup-method method, call Cglib replace the code, and then go to call Getbean, the specific method did not study, have time to see//org.springfraMework.beans.factory.support.cglibsubclassinginstantiationstrategy.lookupoverridemethodinterceptor#intercept @ Override public Object Intercept (object obj, Method method, object[] args, Methodproxy MP) throws Throwable {//Cast
is safe, as Callbackfilter filters is used selectively.
Lookupoverride lo = (lookupoverride) getbeandefinition (). Getmethodoverrides (). Getoverride (method); Object[] Argstouse = (args.length > 0? args:null); If no-arg, don ' t insist on args @ all if (Stringutils.hastext (Lo.getbeanname ())) {//There are beanname, priority use Beannam
E matches return This.owner.getBean (Lo.getbeanname (), argstouse); } else {//did not configure Beanname, try to use type to match, if match to multiple, will throw exception return This.owner.getBean (Method.getreturntype (), argst
OUSE); }
}4.2 Configuring Lookup-methodXML configuration
<bean id= "Person" class= "Com.springapp.mvc.service.Person" >
<lookup-method bean= "Apple" name= " Getapple "/>
</bean>
annotation configuration, using @lookup to configure before method
@Lookup public
Apple getapple () {
//method body is automatically implemented by spring to
return null;
}
Once configured, test it:
//Example 4.1 @Component public class Person {public person () {System.out.println (' person
Initialize ... ");
} public void Eat () {Apple Apple = getapple ();
System.out.println ("Apple hashcode=" +apple.hashcode ()); } public static void Main (String args[]) {beanfactory beanfactory = new Classpathxmlapplicationcontext ("Mvc-di
Spatcher-servlet.xml ");
SYSTEM.OUT.PRINTLN ("Container initialization complete");
Person Person1 = (person) beanfactory.getbean ("person");
Person Person2 = (person) beanfactory.getbean ("person");
Person1.eat ();
Person2.eat ();
} @Lookup Public Apple getapple () {return null;
}} Test output: Person initialization ...
Container initialization complete Apple initialization ...
Apple hashcode=1528848756 Apple initialization ... Apple hashcode=719205737
In contrast to examples 4.1 and 3.1, you can see the features that have been recreated every time Apple is called, and of course, one might ask, what is the difference between writing a method body to implement Getapple, and going to a new object? Or to understand the decoupling, the benefit of this writing is that Apple's creation is still handed to Spring,person, which does not depend on Apple's implementation. Second, the bean implementation process 1. Flowchart
The first one is the old diagram, where the process of creating a bean will go through when the container is initialized with Beanfactory. If you use ApplicationContext, there will be a lot of extra processing and functionality.
2.Spring Source code, the creation and initialization of beans
Org.springframework.beans.factory.support.abstractbeanfactory#dogetbean protected <T> T Dogetbean (final String name, Final class<t> requiredtype, final object[] args, Boolean typecheckonly) throws Beansexcep
tion {... return Createbean (Beanname, mbd, args);
...
} Org.springframework.beans.factory.support.abstractautowirecapablebeanfactory#createbean/** * Central method of this
Class:creates a Bean instance, * Populates the bean instance, applies post-processors, etc. * @see #doCreateBean */@Override protected Object Createbean (final String beanname, final rootbeandefinition mbd, fin Al object[] args) throws Beancreationexception {//Find Bean related classes//Make sure beans class is actually resolve
D at the this point.
Resolvebeanclass (mbd, beanname);
Prepare method Overrides.
...//Check for overloads (literal meaning, non-object inheritance) method exists mbd.preparemethodoverrides (); Give Beanpostprocessors a chance to return a proxy INstead of the target bean instance.
Object bean = resolvebeforeinstantiation (Beanname, mbd);
...//create bean Object beaninstance = Docreatebean (Beanname, mbd, args);
... return beaninstance; }/** * Actually create the specified bean. Pre-creation processing have already happened * at the point, e.g. checking {@code postprocessbeforeinstantiation} cal
Lbacks.
* <p>differentiates between default bean instantiation, use of a * factory method, and autowiring a constructor. * @param beanname The name of the bean * @param mbd the merged bean definition for the bean * @param args arg Uments to use if creating a prototype using explicit arguments to A * static Factory method.
This parameter must is {@code null} except in the this case. * @return A new instance of the bean * @throws beancreationexception if the bean could not be created *//real Create Bea where n is protected Object Docreatebean (final String beanname, final RootbeandefinitiOn MBD, final object[] args) {//instantiate the Bean.
...//create bean instance, call constructor Instancewrapper = Createbeaninstance (Beanname, mbd, args);
...//Properties set Populatebean (Beanname, MBD, Instancewrapper); .../* Org.springframework.beans.factory.support.abstractautowirecapablebeanfactory#initializebean initialize beans in order Includes: 1.beannameaware,beanclassloaderaware,beanfactoryaware of the corresponding interface method 2.BeanPostProcessor preprocessing Postprocessbeforei Nitialization 3.InitializingBean Interface for Afterpropertiesset 4. Custom Init-method method 5.BeanPostProcessor post-processing p
Ostprocessafterinitialization */exposedobject = Initializebean (Beanname, Exposedobject, mbd);
...//Register bean as disposable.
Register Disposablebean, only for singleton bean processing registerdisposablebeanifnecessary (beanname, Bean, mbd);
return exposedobject; } 3. Test Code
public class person implements Beannameaware,beanfactoryaware,beanclassloaderaware,initializingbean,disposablebean
, Applicationcontextaware {public person () {System.out.println ("person initialization ..."); } public static void Main (String args[]) {beanfactory beanfactory = new Classpathxmlapplicationcontext ("Mvc-di
Spatcher-servlet.xml ");
SYSTEM.OUT.PRINTLN ("Container initialization complete");
Person person = (person) beanfactory.getbean ("person");
person = null; } @Override public void Setbeanclassloader (ClassLoader ClassLoader) {System.out.println ("Beanclassloader
Aware Setbeanclassloader () method injected classloader,hashcode= "+classloader.hashcode ()); } @Override public void Setbeanfactory (Beanfactory beanfactory) throws Beansexception {System.out.printl
N ("Beanfactoryaware setbeanfactory () method injects beanfactory,hashcode=" +beanfactory.hashcode ()); } @Override public void Setapplicationcontext (ApplicationContext applicationcontext)Throws Beansexception {//applicationcontext to initialize the container, there will be a lot of additional processing and functionality System.out.println ("Applicationcontextaware
Setapplicationcontext () method to inject applicationcontext,hashcode= "+applicationcontext.hashcode ()); } @Override public void Setbeanname (String name) {System.out.println ("Beannameaware setbeanname () method name,
Name= "+name);
} @Override public void Destroy () throws Exception {System.out.println ("Disposablebean destory () method"); } @Override public void Afterpropertiesset () throws Exception {System.out.println ("Initializingbean A
Fterpropertiesset () method ");
} @PostConstruct public void Postconstruct () {System.out.println ("@PostConstruct annotations");
} public void Initmethod () {System.out.println ("Init-method configuration");
}} Test output: Person initialization ... Beannameaware setbeanname () method Name,name=person Beanclassloaderaware Setbeanclassloader () method injection Classloader,hashcode =918884489 Beanfactoryaware's setbeanfactory () partyInjection of ApplicationContext into the Setapplicationcontext () method injected by beanfactory,hashcode=1574407511 Applicationcontextaware, hashcode=916347070 Beanpostprocessor preprocessing method, Beanname=person @PostConstruct annotation Initializingbean afterpropertiesset ()
Method Init-method Configuration Beanpostprocessor post-processing method, Beanname=person4. Summary
Spring provides many ways to intervene during the initialization of a bean, but it is generally not recommended to implement the spring interface, such as implementing Initializingbean, Instead, use @postconstruct annotations or custom Init-method configurations because the implementation interface is coupled with spring.