Spring Load Bean Instantiation order

Source: Internet
Author: User

Reprint: http://blog.sina.com.cn/s/blog_525960510100ipwj.html

Http://blog.sina.com.cn/s/blog_6940cab30102uwma.html

Source of the problem:

A bean is a and a bean is B. A property that you want a to instantiate in a container name is a method that assigns a value of B to the return value of Funb.

If it's simply written in a:

Private b b;
Private String name = B.funb ();

will give an error saying nullpointexception, because this time B has not been set in, so null.

The solution is the following code, while learning the following spring in Initializingbean , object construction methods , Init-method execution order.

public class A implements Initializingbean {

Private b b;
private String name; = B.funb ();

public void Setb (b b) {
System.out.println ("A.setb initialed");
this.b = b;
}

Public A () {
System.out.println ("A initialed");
}

public void init () {
System.out.println ("Init");
THIS.name = B.funb ();
}

@Override
Public String toString () {
return super.tostring () + this.name;
}

public void Afterpropertiesset () throws Exception {

Actually, it can be put here.

THIS.name = B.funb ();
System.out.println ("Afterpropertiesset");

}

}

public class B {

Public String Funb () {
System.out.println ("Funb");
return "B.funb";
}

Public B () {
System.out.println ("B initialed");
}
}

Spring configuration file

<beans default->
<bean id= "A" class= "testspring. A "init-method=" init ">
</bean>
<bean id= "B" class= "testspring. B ">
</bean>
</beans>

Test code:

public static void Main (string[] args) {
ApplicationContext context = new Filesystemxmlapplicationcontext (
"Src/testspring/bean.xml");
A = (a) Context.getbean ("a");
System.out.println (a);

}

The program output is:

A initialed
B initialed
A.setb initialed
Afterpropertiesset
Init
Funb
[Email protected]

From here we see that the name property of a is successfully set to the return value of the Funb method of B when the bean is loaded, and the main point is to use Init-method to implement it.

The load order can also be seen as:

The first constructor--and then the set method of B--Initializingbean Afterpropertiesset Method----Init-method method

Summarized as:

The following are excerpts from the book, but I find that even if you extract them again, the understanding of their contents will be deeper!
First, spring Assembly bean process
1. Instantiation;
2. Set the attribute value;
3. If the Beannameaware interface is implemented, call Setbeanname to set the bean ID or name;
4. If the Beanfactoryaware interface is implemented, call Setbeanfactory to set the beanfactory;
5. If you implement Applicationcontextaware, call Setapplicationcontext settings ApplicationContext
6. Call the pre-initialization method of the Beanpostprocessor;
7. Call Initializingbean's Afterpropertiesset () method;
8. Call the custom Init-method method;
9. Call the Post-initialization method of beanpostprocessor;


Spring Container shutdown process
1. Call Disposablebean's Destroy ();
2. Call the custom Destroy-method method;

==========================

Spring Initializingbean Init-method postconstruct Execution Order:

The beans in the spring container are life-cycle, and spring allows specific operations to be performed after the bean has been initialized and before the bean is destroyed, with the following three types of settings commonly used:  by implementing initializingbean/ Disposablebean interface to customize the operation method after initialization/destruction, specifying the action method to be called after initialization/destruction via the element's Init-method/destroy-method property; adding @postconstruct to the specified method; or @predestroy annotations to make the method be called after initialization or before destruction.   This is the question we have, these three ways is exactly the same, the first and the right after?   Below we will take this question and try to find the answer by testing the code and analyzing the spring source.   First, let's write a simple test code:  java code Copy Code Collection code public class Initsequencebean implements Initializingbean {           public Initsequencebean () {          system.out.println ("Initsequencebean:constructor");       }             @ Postconstruct      public void Postconstruct () {          system.out.println ("Initsequencebean:postconstruct");       }             public void Initmethod () {          system.out.println ("Initsequencebean:init-method");       }             @ Override      public void Afterpropertiesset () throws Exception {          system.out.println ("Initsequencebean:afterpropertiesset");       }         and add the following bean definition in the configuration file:      Well, we start the spring container and observe the output, so we know the order of the three:  initsequencebean:constructor initsequencebean: postconstruct initsequencebean:afterpropertiesset initsequencebean:init-method  through the above output results, The order of the three is also at a glance:  constructor > @PostConstruct > Initializingbean > init-method  Let's start with a rough analysis of why these results occur: the constructor (Constructor) is first invoked without doubt, Initializingbean before Init-method we can also understand (in also talking about spring containerhas been discussed in the life cycle of the postconstruct, but why did the first Initializingbean execute it?   We're going to look at the spring source code again with this question. By debugging and looking at the call stack, We have found this class of org.springframework.context.annotation.CommonAnnotationBeanPostProcessor, and from the name we can get some information-- This is a beanpostprocessor. What did you think of? In the life cycle of the spring container, We have mentioned that the postprocessbeforeinitialization of Beanpostprocessor is called before Afterpropertiesset and Init-method in the bean life cycle.   Again observe the Commonannotationbeanpostprocessor class, which inherits from Initdestroyannotationbeanpostprocessor. Initdestroyannotationbeanpostprocessor, as the name implies, is a pre/post processor that was made when the bean was initialized and destroyed.   by looking at the Postprocessbeforeinitialization method under the Initdestroyannotationbeanpostprocessor class:  java Code Copy Code Favorite Code public Object Postprocessbeforeinitialization (object bean, String beanname) throws Beansexception {  & Nbsp;      lifecyclemetadata metadata = Findlifecyclemetadata (Bean.getClass ());          try {              metadata.invokeinitmEthods (bean, beanname);          }           catch (InvocationTargetException ex) {              throw New Beancreationexception (Beanname, "Invocation of Init method failed", Ex.gettargetexception ());          }           catch (Throwable ex) {             throw new Beancreationexception (Beanname, "couldn ' t invoke init method", ex);          }            return Bean;       }      view Findlifecyclemetadata method, Then we trace to buildlifecyclemetadata this method body, look at the content of Buildlifecyclemetadata this method body:  java code Copy Code Collection code private Lifecyclemetadata Buildlifecyclemetadata(Final Class Clazz) {         final Lifecyclemetadata newMetadata = new LifecycleMetadata ( );          final Boolean debug = logger.isdebugenabled ();          reflectionutils.dowithmethods (Clazz, new Reflectionutils.methodcallback () {              public void Dowith (method) {                 if (Initannotationtype! = null) {                     if (Method.getannotation (initAnnotationType)! = null) {                        newmetadata.addinitmethod (method);       &Nbsp;                if (Debug) {                            logger.debug ("Found init method on class [" + Clazz.getname () + " ]: "+ method);                         }                      }                  }                  if (Destroyannotationtype! = null) {                     if (Method.getannotation (destrOyannotationtype) = null) {                        newmetadata.adddestroymethod (method);                         if (Debug) {                            logger.debug (" Found destroy method on class ["+ Clazz.getname () +"]: "+ method);                         }                      }                  }              }          });          return Newmetadata;   }    Analysis This code finds that there is a way to judge whether a method has been initannotationtype/destroyannotationtype annotated, and if so, adds to init/ The destroy queue, followed by one by one execution. What is  initannotationtype/destroyannotationtype comment, we see this code in the Commonannotationbeanpostprocessor constructor:  Java code Copy Code Collection Code public Commonannotationbeanpostprocessor () {          Setorder (ordered.lowest_precedence-3);          setinitannotationtype (PostConstruct.class);          setdestroyannotationtype (PreDestroy.class);          ignoreresourcetype ("Javax.xml.ws.WebServiceContext"); &NBSP;&NBSP:}      everything is clear. Word, @PostConstruct Annotated method is executed in the Beanpostprocessor pre-processor, so of course it precedes Initializingbean and Init-meThod carried out.   Finally, the paper concludes that the bean is instantiated in the process:  constructor > @PostConstruct > Initializingbean > Init-method

Spring Load Bean instantiation order

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.