Spring in Initializingbean interface use understanding

Source: Internet
Author: User

The Initializingbean interface provides a way for the bean to initialize the method, which includes only the Afterpropertiesset method, which is the class that inherits the interface, and executes the method when the bean is initialized.

The test procedure is as follows:

Import Org.springframework.beans.factory.InitializingBean;  Public class Implements initializingbean{    @Override    publicvoidthrows  Exception {        System.out.println ("Ceshi Initializingbean");            }      Public void Testinit () {        System.out.println ("Ceshi init-method");}            }

The configuration file is as follows:

class= "com. Testinitializingbean "></bean>

Main program is as follows:

 Public class Main {    publicstaticvoid  main (string[] args) {        new Filesystemxmlapplicationcontext ("/src/main/java/com/beans.xml");}    }

Run the main program and print the following results:

Ceshi Initializingbean

This means that when spring initializes the bean, the Afterpropertiesset method is called automatically if the Bean implements the Initializingbean interface.

Problem

What is the difference between implementing the Initializingbean interface and specifying Init-method in the configuration file?

Modify the configuration file, plus the Init-method configuration, as follows:

class= "com. Testinitializingbean "init-method=" Testinit "></bean>

Add init-method= "Testinit" to the configuration file.

Run the main program and print the following results:

Ceshi Initializingbeanceshi Init-method

As the result shows, when spring initializes the bean, if the bean implements the Initializingbean interface, and the Init-method is specified in the configuration file, the system calls the Afterpropertiesset method first. Then specify the method in the call Init-method.

How does this approach be implemented in spring?

By looking at the source Class (Abstractautowirecapablebeanfactory) of spring's load bean, you can see the secret

Abstractautowirecapablebeanfactory class in the Invokeinitmethods explained very clearly, the source code is as follows:

protected voidInvokeinitmethods (String Beanname,FinalObject Bean, rootbeandefinition mbd)throwsThrowable {//determine if the bean implements the Initializingbean interface, and if the Initializingbean interface is implemented, only the Afterpropertiesset method of invoking the bean is dropped .    BooleanIsinitializingbean = (beaninstanceofInitializingbean); if(Isinitializingbean && (mbd = =NULL|| !mbd.isexternallymanagedinitmethod ("Afterpropertiesset"))) {        if(logger.isdebugenabled ()) {Logger.debug ("Invoking Afterpropertiesset () on beans with name '" + beanname + "'"); }                 if(System.getsecuritymanager ()! =NULL) {            Try{accesscontroller.doprivileged (NewPrivilegedexceptionaction<object>() {                     PublicObject Run ()throwsException {//Call Afterpropertiesset directly( (Initializingbean) bean). Afterpropertiesset (); return NULL;            }},getaccesscontrolcontext ()); } Catch(privilegedactionexception PAE) {Throwpae.getexception (); }        }                        Else {            //Call Afterpropertiesset directly( (Initializingbean) bean). Afterpropertiesset (); }    }    if(mbd! =NULL) {String initmethodname=Mbd.getinitmethodname (); //determines whether the Init-method method is specified, and if the Init-method method is specified, then calls the established Init-method        if(Initmethodname! =NULL&&! (Isinitializingbean && "Afterpropertiesset". Equals (Initmethodname)) &&!Mbd.isexternallymanagedinitmethod (Initmethodname)) {            //To see the source of the method further, you can see that the method specified in the Init-method method is implemented by reflectionInvokecustominitmethod (Beanname, Bean, mbd); }    }}

Summarize

1:spring provides two ways for the bean to initialize the bean, implement the Initializingbean interface, implement the Afterpropertiesset method, or specify it with Init-method in the configuration file, both of which can be used simultaneously

2: Implementing the Initializingbean interface is a direct call to the Afterpropertiesset method, which is more efficient than the method specified by the reflection call Init-method. But the Init-method approach eliminates the reliance on spring.

3: If an error occurs when calling the Afterpropertiesset method, the method specified by Init-method is not called.

Spring in Initializingbean interface use understanding

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.