Spring Kernel Research-managing bean Declaration cycles One (Initializingbean and Init-method)

Source: Internet
Author: User
Tags throwable
Spring Kernel Research-managing bean Declaration cycles One (Initializingbean and Init-method)
Initializingbean SPIRNG'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 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. P Rintln ("Lifecyclebean initializing ...)   " ); } } You do not need to make a special configuration of the bean in an 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>
To 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 Cla Sspathresource (
"Research/spring/beanfactory/ch4/context.xml")); Factory.getbean ("Lifebean");}
Running the above program we will see: "Lifecyclebean initializing ...", which indicates that the bean's afterpropertiesset has been invoked by spring. When spring finishes setting up all of the partners for a bean, it checks to see if the Bean implements the Initializingbean interface, and calls the Bean's Afterpropertiesset method if it is implemented.

SHAPE/* MERGEFORMAT

partner who assembles the Bean

To see if the bean implements the Initializingbean interface

Calling the Afterpropertiesset method


Init-method Although spring can complete a callback to this bean after a bean initialization through initializingbean, this way requires the bean to implement the Initializingbean interface. Once the bean implements the Initializingbean interface, the bean's code is coupled with spring. Normally I do not encourage beans to implement initializingbean directly, and you can use the Init-method functionality provided by spring to perform an initialization method of a bean's child definition. Write a Java class that does not implement any spring interfaces. Defines a method init () with no parameters.
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 will see "Lifecyclebean.init ..." on the console. Spring requires Init-method to be a parameterless method, and if there are parameters in the method specified by Init-method, spring will throw java.lang.NoSuchMethodException   Init-method the method specified 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, 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, then spring aborts the subsequent processing of the bean and throws a Org.springframework.beans.factory.BeanCreationException exception. Initializingbean and Init-method can be used together, and spring will deal with Initializingbean and then process Init-method first. Org.springframework.beans.factory.support. Abstractautowirecapablebeanfactory completes the invocation of a bean initialization method. Abstractautowirecapablebeanfactory is a super class of xmlbeanfactory, and then The implementation of the Abstractautowirecapablebeanfactory Invokeinitmethods method calls a bean initialization method: Org.springframework.beans.factory.support. Abstractautowirecapablebeanfactory.java:

...//After a bean's collaborators device completes, executes a bean initialization method. protected void Invokeinitmethods (String beanname, Object Bean, rootbeandefinition mergedbeandefinition)
 throws Throwable {//Determines whether the bean implements the Initializingbean interface if (bean instanceof Initializingbean) {if (logger.isdebugenabl Ed ()) {Logger.debug ("invoking Afterpropertiesset () on beans with name" + Beanname + "");} Call the Afterpropertiesset method ((Initializingbean) bean). Afterpropertiesset (); //Determine if the bean defines Init-method if (mergedbeandefinition!= null && mergedbeandefinition.getinitmethodname ()!= null {//Call the Invokecustominitmethod method to perform Init-method defined method Invokecustominitmethod (Beanname, Bean, Mergedbeandefinition.getinitmethodname ()); }//execute 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 +" ' ");} Using the method name, Reflection Methods Object Method Initmethod = Beanutils.findmethod (Bean.getclass (), initmethodname, NULL); if (Initmethod = = null) {throw new NosuchmethodexceptioN
"Couldn ' t find is init method named '" + Initmethodname + "' in Bean with Name '" + Beanname + "");} Determine if the method is public if (! Modifier.ispublic (Initmethod.getmodifiers ())) {//Set accessible to true to access private methods. Initmethod.setaccessible (TRUE); try {//Reflection executes this method Initmethod.invoke (bean, (object[]) null);} catch (InvocationTargetException ex) {throw ex.gettarget Exception (); } } // ...........
By analyzing the source code above, we can see that the Init-method is performed through reflection, and the afterpropertiesset is executed directly. So afterpropertiesset execution is more efficient than init-method, but Init-method eliminates the bean dependency on spring.     I recommend using Init-method in actual use. It is to be noted that spring always processes the initializingbean of the bean definition before processing the init-method.     If an error occurs while SPIRNG handles Initializingbean, spring throws an exception directly and does not continue to process the init-method. If a bean is defined as not a single case, then Afterpropertiesset and Init-method are executed when each instance of the bean is created. The Afterpropertiesset and Init-method of a single instance bean are only invoked once for the first time that the bean is instantiated. In most cases afterpropertiesset and Init-method are applied on a single instance of the bean.
Posted on July 5, 2006 18:01 by Chen Jie 0 reviewsSpring Kernel Research-managing the relationship between beans three (automatic assembly)

Spring Beanfactory provides functionality similar to objects that are dependent on automatic assembly components in Pico container.     Automatic assembly can be applied on each component, can define automatic assembly for some components, and others are not used. Use the "Autowire" property to set up automatic assembly, Autowire has five modes : no default property, no automatic assembly. byname automatically assembles collaborators through the Bean's property name.

SHAPE/* MERGEFORMAT

automatically assemble according to the name defined by the bean


Spring uses the name of the set method in the bean to match the names of the collaborators defined in the Beanfactory, and when one or 2 matches, Sping injects the collaborators. You can also use the id attribute to define the name of a partner by using the Name property, which makes no difference when spring is automatically assembled. When more than one partner with the same name is defined in spring, srping selects the last defined partner injection when the assembly is automatically assembled.

SHAPE/* MERGEFORMAT

This bean will be injected into the DAO


When multiple collaborators are automatically assembled with the same name, the partner's ID attribute is not treated more preferentially than the name attribute. No matter how you define spring, the last defined partner is injected.
Bytype By matching the type of the parameter in the Bean set method with the type of the partner defined in Beanfactory, spring will find the matching partner to inject.

SHAPE/* MERGEFORMAT

automatically assemble according to the type defined by the bean


In Bytype automatic assembly mode, spring does not care about the name of the partner, but only the type of the partner satisfies the condition. Similar to the byname approach described above, in the bytype approach,when multiple collaborators with the same name and with the same typeWhen found, spring injects the last defined partner.

SHAPE/* MERGEFORMAT

This bean will be injected into the DAO


When Bytype is assembled, spring throws a dependency exception if 2 different names but the same type of collaborators are found.

SHAPE/* MERGEFORMAT


Throws a dependency exception, notifying the user that the same type of bean can only be defined in the Bytype way.

Org.springframework.beans.factory.UnsatisfiedDependencyException:Error creating Bean with Name ' DAO ' defined in class Path resource [Research/spring/beanfactory/ch3/context.xml]: Unsatisfied dependency expressed bean property ' Database ': There are 2 beans of type [class Research.spring.beanfactory.ch3.Database] for Autowire by type. There should have been 1 to is able to autowire property ' database ' of bean ' dao ' ... Constructor

Constructor in fact, the constructor is injected in a bytype manner.

SHAPE/* MERGEFORMAT

automatically assemble according to the type defined by the bean



The constructor assembly method does not care about the order of the constructor parameters, regardless of the order of the constructor parameters spring will be injected by type to the correct collaborators. In the Bytype way, spring will not do anything when no collaborators of the same type are found.     But in the constructor way, spring throws an exception when no collaborators are found that match the parameter types in the Bean constructor. When spring makes automatic assembly of constructor, it forces all the collaborators in all constructors to exist.
AutoDetect In the AutoDetect way, spring checks whether a bean has a default constructor inside it. If there is a default parameter spring, automatic assembly is done using the Bytype method. If there is no default constructor spring, it is automatically assembled using the constructor method.         If a bean defines both a default constructor and a constructor with parameters, spring will still be assembled using the Bytype method. The definition collaborators that can be displayed in the bean, regardless of which assembly method is used. Shows that the dependency priority for the definition is higher than the automatic assembly. The automatic assembly function can be used with automatic dependency checking. Spring is first assembled automatically, and then on dependency checking. Automatic Assembly provides the possibility of simplifying configuration, but I do not recommend a lot of use of automatic assembly in the project, especially when the Bytype mode. Because automatic assembly, especially when Bytype way, destroys the dependencies that are displayed between the bean and the collaborators, all dependencies are not obvious. Our dependencies need to be visible in the source code after using automatic assembly, which makes it difficult to maintain or document the Bean dependencies. Proper use of automatic assembly, such as ByName assembly, is of some benefit. For example, we can use the ByName automatic assembly function in some specific scopes to realize "Replace configuration with conventions"The framework. Posted on July 4, 2006 17:17 by Chen Jie 0 reviewsSpring Kernel Research-managing the relationship between beans two (automatic dependency checking)Automatic dependency checking ensures that properties (set methods) in all Java beans are properly configured in spring. If a Name property is defined in a Java bean, the method is also setname. Then after you turn on automatic dependency checking, you must define this property in spring, or spring will throw an exception. Take a look at the following example:Dao.javaContains a SetName method.
Package Research.spring.beanfactory.ch3; public class Dao {private String name, public void SetName (String name) {this. name = name;}}
context.xml
? 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 = "DAO" C

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.