Spring Bean initialization Initializingbean, Init-method and Postconstruct

Source: Internet
Author: User
Overview

It is not difficult to find out from the name of the interface that the function of Initializingbean is to perform a custom operation after the bean is initialized.

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 common settings: by implementing the Initializingbean/disposablebean interface to Custom initialization/destruction before/after operation; Specifies the action method to be called after initialization/destruction by the Init-method/destroy-method attribute of the <bean> element; Adding @postconstruct to the specified method; or @predestroy annotations to make the method be called after initialization or before destruction.

Note: The following source code analysis is based on spring 5.0.4 Initializingbean vs Init-method

The interface is defined as follows:

Public interface Initializingbean {
    void Afterpropertiesset () throws Exception;
}

Interface has only one method Afterpropertiesset, the invocation of this method is responsible for loading the spring Bean abstractautowirecapablebeanfactory, the source code is as follows:

    protected void Invokeinitmethods (String beanname, Final Object Bean, @Nullable rootbeandefinition mbd) thr
        oWS Throwable {Boolean isinitializingbean = (bean instanceof Initializingbean);
            if (Isinitializingbean && (mbd = = NULL | |!mbd.isexternallymanagedinitmethod ("afterpropertiesset"))) { if (logger.isdebugenabled ()) {Logger.debug ("invoking Afterpropertiesset () on beans with name '" + Beannam
            E + "'"); } if (System.getsecuritymanager () = null) {try {Accesscontroller.dopriv Ileged ((privilegedexceptionaction<object>) (), {((Initializingbean) bean). Afterpropert
                        Iesset ();
                    return null;
                }, Getaccesscontrolcontext ());
                } catch (Privilegedactionexception pae) {throw pae.getexception ();
 }} else {               ((Initializingbean) bean). Afterpropertiesset (); }
        }

The following conclusions can be drawn from this source: Spring provides two ways for the bean to initialize the bean, implement the Initializingbean interface, implement the Afterpropertiesset method, or specify it through Init-method in the configuration file. Two ways to implement the Initializingbean interface using both methods are to call the Afterpropertiesset method directly, which is more efficient than the method specified by the reflection call Init-method. However, the Init-method method eliminates the dependency on spring by calling Afterpropertiesset first, then executing Init-method methods, and if an error occurs when calling the Afterpropertiesset method, The method specified by Init-method is not called. @PostConstruct

Find the class initdestroyannotationbeanpostprocessor through the debug and call stack, where the core method, which is the entry @PostConstruct method invocation:

 @Override public object Postprocessbeforeinitialization (object bean, String beanname) throws Beansexception {
        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, "Failed to invoke Init method", ex)
        ;
    } return bean; }

From the name, we can get some information--this is a beanpostprocessor. Think of anything. In the life cycle of the spring container, References to Beanpostprocessor postprocessbeforeinitialization are called before Afterpropertiesset and Init-method in the bean life cycle. In addition, by tracing, @PostConstruct method is also called through the launch mechanism. summarizes the initialization execution order of spring beans: Constructs a method--@PostConstruct annotations--and Afterpropertiesset Method---Init-method the specified method. Refer to the example afterpropertiesset by the interface implementation of the call (high efficiency point), @PostConstruct and Init-method are all through the reflection mechanism invocation Example

Direct execution of single test com.skyarthur.springboot.common.bean.InitSequenceBeanTest, please poke code download address

The core code is as follows:

@Slf4j public class Initsequencebean implements Initializingbean {public Initsequencebean () {Log.info ("Init
    Sequencebean:construct "); } @Override public void Afterpropertiesset () throws Exception {Log.info ("Initsequencebean:afterproperti
    Esset ");
    } @PostConstruct public void Postconstruct () {log.info ("initsequencebean:postconstruct");
    } public void Initmethod () {log.info ("Initsequencebean:initmethod"); }} @Configuration public class Systemconfig {@Bean (Initmethod = "Initmethod", name = "Initsequencebean") publi
    C Initsequencebean Initsequencebean () {return new Initsequencebean (); }} @Slf4j public class Initsequencebeantest extends Applicationtests {@Autowired private Initsequencebean init

    Sequencebean;
    @Test public void Initsequencebeantest () {Log.info ("Finish: {}", initsequencebean.tostring ()); }
}
Published on March 31

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.