Translated from: http://blog.csdn.net/shaozheng1006/article/details/6916940
The Initializingbean of Initializingbean Spirng provides a way for the bean to define the initialization method. Initializingbean is an interface that contains only one method: Afterpropertiesset ().
After spring initialization, execution of all property-setting methods (that is, setxxx) will automatically call Afterpropertiesset (), which does not require special configuration in the configuration file, but this method increases the bean's dependency on spring and should try to avoid using SPIRNG's Initializingbean provides a way for the bean to define the initialization method. Initializingbean is an interface that contains only one method: Afterpropertiesset ().
public interface Initializingbean
{
public abstract void Afterpropertiesset ()
Throws Exception;
}
The bean implements this interface and writes the initialization code in Afterpropertiesset ():
Package Research.spring.beanfactory.ch4;import Org.springframework.beans.factory.initializingbean;public Class Lifecyclebean implements Initializingbean{public 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 ">bean>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 {public static void main (string[] args) { Xmlbeanfactory factory=new xmlbeanfactory (New Classpathresource ("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 |
Init-method Spring Although it is possible to complete a callback for this bean after the bean is initialized by Initializingbean, this method 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;public class Lifecyclebean{public void 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 ">bean>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 is completed, a bean 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 + "'");} Call the Afterpropertiesset method ((Initializingbean) bean). Afterpropertiesset ();} Determines whether the bean defines INIT-METHODIF (mergedbeandefinition!=null&&mergedbeandefinition.getinitmethodname () = null) {//Call the Invokecustominitmethod method to execute Init-method defined 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 bean Wit H name ' "+ beanname +" ' ");} Using the method name, Reflection Method Object method Initmethod = Beanutils.findmethod (Bean.getclass (), initmethodname, null), if (Initmethod = = null) {throw new Nosuchmethodexception ( "couldn ' t Find a Init method named ' "+ Initmethodname +" ' on Beans with Name ' "+ beanname +" ' ");} Determine if the method is Publicif (! Modifier.ispublic (Initmethod.getmodifiers ())) {//Set accessible to true to have access to the private method. Initmethod.setaccessible (TRUE);} try {//Reflection executes 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.
< two >
Init-method
Write a public method with no parameters and no return value in the bean to implement the bean initialization. For example
public void init () {
...... Initialize Code
}
After spring initialization, execution of all property setting methods (that is, setxxx) will automatically invoke the configuration file Init-method the specified method, as shown in the configuration file
<bean name= "Beanname" class= "Package.bean" init-method= "init" > </bean>
< three >
The Initializingbean interface is provided by spring, and the subclass implements the Afterpropertiesset () method, init-method the user can configure through the properties file. From here we can see that the implementation of the Initializingbean interface is to be coupled with spring, while the Init-method is not. But the Afterpropertiesset () method spring can invoke execution directly, Init-method the specified method needs to be performed by reflection, and is not afgerpropertiesset () faster than efficiency. Initializingbean and Init-method can be used together, and spring will process the Initializingbean before processing Init-method.
Here is a small example, Initializingbean interface and Init-method are implemented, you can easily change.
The bean for the test:
Package researchspring.beanfactory;
Import Org.springframework.beans.factory.InitializingBean;
public class Lifecyclebean implements initializingbean{
private String name;
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public void Afterpropertiesset () throws Exception {
System.out.println ("Implements initializing start ...");
if (name = = NULL)
System.out.println ("Configuration failed!");
System.out.println ("Implements initializing end!");
}
public void init () {
System.out.println ("Init () initializing start ...");
if (name = = NULL)
System.out.println ("Configuration failed!");
System.out.println ("Init () initializing end!");
}
}
Applicationcontext.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<beans
Xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd ">
<bean id= "Lifebean" class= "Researchspring.beanfactory.LifeCycleBean"
init-method= "Init" >
<property name= "name" value= "Apple" ></property>
</bean>
</beans>
Test class:
public class Test {
public static void Main (string[] args) {
ApplicationContext ac = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Lifecyclebean Lifebean = (Lifecyclebean) ac.getbean ("Lifebean");
}
}
Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
In addition, from the Internet to find such a paragraph
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 is completed, a bean initialization method is executed. protected void Invokeinitmethods (String beanname, Object Bean, rootbeandefinition mergedbeandefinition) throws Throwable {//Determines if the bean implements the Initializingbean interface if (bean instanceof Initializingbean) {if (logger.isdebugenabled ()) { Logger.debug ("Invoking Afterpropertiesset () on beans with name '" + beanname + "'");} Call the Afterpropertiesset method ((Initializingbean) bean). Afterpropertiesset ();} Determines whether the bean defines INIT-METHODIF (mergedbeandefinition!=null&&mergedbeandefinition.getinitmethodname () = null) {//Call the Invokecustominitmethod method to execute Init-method defined 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 bean With Name ' + Beanname + ' ");} Using method Name, Reflection Method Object Method Initmethod = Beanutils.findmethod (bean.getclaSS (), Initmethodname, NULL), if (Initmethod = = null) {throw new Nosuchmethodexception ("couldn ' t find an init method named ' "+ Initmethodname +" ' on Beans with Name ' "+ beanname +" ' ");} Determine if the method is Publicif (! Modifier.ispublic (Initmethod.getmodifiers ())) {//Set accessible to true to have access to the private method. Initmethod.setaccessible (TRUE);} try {//Reflection executes this method Initmethod.invoke (bean, (object[]) null);} catch (InvocationTargetException ex) {throw ex.gettargetexception ();}} ...........
Spring Initializingbean and Init-method