Initializingbean and Init-method

Source: Internet
Author: User

"Spring's Initializingbean Afterpropertiesset method and the Init-method configuration of the difference link"

Initializingbean

Spring's Initializingbean provides a way for the bean to define the initialization method . Initializingbean is an interface that contains only one method:afterpropertiesset().

The bean implements this interface and writes the initialization code in Afterpropertiesset ():

Package RESEARCH.SPRING.BEANFACTORY.CH4; Import Org.springframework.beans.factory.InitializingBean; Class Lifecyclebean implements initializingbean{

void Afterpropertiesset () throws Exception {System. Out. println ("Lifecyclebean initializing ...");}

There is no need for special configuration of beans in the XML configuration file:

XML version= "1.0" encoding= "UTF-8"?> DOCTYPE beans Public "-//spring//dtd bean//en" http://www.springframework.org /dtd/spring-beans.dtd ">

< beans >

< bean name = "Lifebean" class = "Research.spring.beanfactory.ch4.LifeCycleBean" >

>

</beans >

Write a test program to test:

Package RESEARCH.SPRING.BEANFACTORY.CH4; Import Org.springframework.beans.factory.xml.XmlBeanFactory; Import Org.springframework.core.io.ClassPathResource; public class Lifecycletest {static void main (string[] args) {xmlbeanfactory factory= newxmlbeanfactory (New Classpathres Ource ("Research/spring/beanfactory/ch4/context.xml")); Factory.getbean ("Lifebean"); } }

Running the above program we will see: "Lifecyclebean initializing ...", which indicates that the bean Afterpropertiesset has been called by spring.

Spring, after setting up all the collaborators of a bean, checks to see if the Bean implements the Initializingbean interface and invokes the Bean's Afterpropertiesset method if implemented.

SHAPE/* MERGEFORMAT

The partner who assembles the bean

See if the Bean implements the Initializingbean interface

Calling the Afterpropertiesset method

Although spring can complete a callback of the bean after the bean is initialized with Initializingbean, this approach requires the bean to implement the Initializingbean interface. once the bean implements the Initializingbean interface, the bean's code is coupled with spring . In general, I do not encourage beans to implement initializingbean directly, and you can use the functionality of the Init-method provided by spring to perform a method of initializing a bean's child definition.

Write a Java class that does not implement any of the spring interfaces. Define a method with no Parameters init ().

Package RESEARCH.SPRING.BEANFACTORY.CH4;

Publicclass lifecyclebean{

Publicvoid Init () {

System. Out. println ("Lifecyclebean.init ...");

}

}

Configure this Bean in spring:

XML version= "1.0" encoding= "UTF-8"?> DOCTYPE beans Public "-//spring//dtd bean//en"

"Http://www.springframework.org/dtd/spring-beans.dtd" >< beans >< Bean name = "Lifebean" class = " Research.spring.beanfactory.ch4.LifeCycleBean "

Init-method = "init" > Beans > Beans >

When spring instantiates Lifebean, you'll see "Lifecyclebean.init ..." on the console.

Spring requires Init-method to be a parameterless method, and if Init-method has parameters in the specified method, spring will throw java.lang.NoSuchMethodException

The method specified by Init-method can be public, protected, and private, and the method can be final.

The method specified by Init-method can be declared as throwing an exception, just like this:

Final protected void init () throws exception{

System.out.println ("Init method ...");

if (true) throw new Exception ("Init Exception");

}

If an exception is thrown in the Init-method method, spring aborts the bean's subsequent processing and throws a Org.springframework.beans.factory.BeanCreationException exception.

Initializingbean and Init-method can be used together, and spring will process the Initializingbean before processing Init-method.

Org.springframework.beans.factory.support. Abstractautowirecapablebeanfactory completes the invocation of a bean initialization method. Abstractautowirecapablebeanfactory is the super class of Xmlbeanfactory, and then The implementation of Abstractautowirecapablebeanfactory in the Invokeinitmethods method calls a bean initialization method:

Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java:

......

After a bean's partner device completes, a bean's initialization method is executed. protected void Invokeinitmethods (String beanname, Object Bean, rootbeandefinition mergedbeandefinition)

Throws Throwable {

Determine if the bean implements the Initializingbean interface if (bean instanceof Initializingbean) {

if (logger.isdebugenabled ()) {

Logger.debug ("Invoking Afterpropertiesset () on beans with name '" + beanname + "'");

}

Calling the Afterpropertiesset method

((Initializingbean) bean). Afterpropertiesset ();

}

Determine if the bean defines Init-method if (mergedbeandefinition!= null &&mergedbeandefinition.getinitmethodname () = null) {

Call the Invokecustominitmethod method to execute the method defined by the Init-method

Invokecustominitmethod (Beanname, Bean, mergedbeandefinition.getinitmethodname ());

} }

Executes a bean-defined Init-method method protected void Invokecustominitmethod (String beanname, Object bean, string initmethodname)

Throws Throwable {

if (logger.isdebugenabled ()) {

Logger.debug ("Invoking custom Init method '" + Initmethodname + "' on Beans with Name '" + beanname + "'");

}

Use method Name, Reflection method Object

Method Initmethod = Beanutils.findmethod (Bean.getclass (), initmethodname, NULL);

if (Initmethod ==null) {

Thrownew Nosuchmethodexception (

"Couldn ' t find a init method named '" + Initmethodname + "' on Beans with Name '" + beanname + "'");

}

Determine if the method is public if (! Modifier.ispublic (Initmethod.getmodifiers ())) {

Set accessible to true to access the private method. Initmethod.setaccessible (TRUE);

}

try {

Reflection performs this method

Initmethod.invoke (Bean, (object[]) null);

}

catch (InvocationTargetException ex) {

Throw Ex.gettargetexception ();

} }

...........

By analyzing the source code above, we can see that the Init-method is performed by reflection, while the afterpropertiesset is executed directly. So Afterpropertiesset's execution efficiency is higher than init-method, but Init-method eliminates the bean's dependence on spring. I recommend using Init-method for practical use.

It is important to note that spring always processes the bean-defined initializingbean before processing Init-method. If an error occurs while SPIRNG is processing Initializingbean, spring throws an exception directly and no longer processes the Init-method.

If a bean is defined as non-singleton, then Afterpropertiesset and Init-method are executed when each instance of the bean is created. The Afterpropertiesset and Init-method of a singleton bean are only called once when the Bean is first instantiated by an instance. In most cases afterpropertiesset and Init-method are applied on a singleton bean.

Initializingbean and Init-method

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.