Important interfaces commonly used in spring

Source: Internet
Author: User
Tags wrapper

Spring (ApplicationContext Initialize Bean Method Refresh ())

public void Refresh () throws Beansexception, IllegalStateException {synchronized (this.startupshutdownmonitor) {// Prepare this context for Refreshing.preparerefresh ();//Tell the subclass to refresh the internal bean factory. Configurablelistablebeanfactory beanfactory = Obtainfreshbeanfactory ();//Prepare The Bean Factory for use with this context . Preparebeanfactory (beanfactory); try {//allows post-processing of the Bean factory in context Subclasses.postprocessbeanfactory (beanfactory);//Invoke factory processors registered as beans in the Context.invokebeanfactorypostprocessors (beanfactory);//Register bean processors that intercept bean creation.// Create Bean and Post methods registerbeanpostprocessors (beanfactory);//Initialize message source for this Context.initmessagesource ();//Initialize Event Multicaster for this context.initapplicationeventmulticaster ();// Initialize other special beans in specific context subclasses.onrefresh ();//Check for listener beans and register them.re Gisterlisteners ();//Instantiate all remaining (Non-lazy-init) singletons.finishbeanfactoryinitialization (beanfactory);//Last step : Publish corresponding Event.finishrefresh ();} catch (Beansexception ex) {//Destroy already created singletons to avoid dangling resources.destroybeans ();//Reset ' ACTI ve ' Flag.cancelrefresh (ex);//Propagate exception to Caller.throw Ex;}}}

  

The Spring framework wants to customize some logic in the bean's initialization phase, or to get some resources, a very useful interface that has

beanpostprocessor,//Properties is set to complete, Initializingbean afterpropertiesset (), and after Init-method is complete, some logical processing of the bean

initializingbean,//provides Afterpropertiesset (), which is called before Init-method (both methods can be used to implement the Bean Init method);

Destructionawarebeanpostprocessor,//postprocessbeforedestruction (Object Bean, String beanname) method is called before the Destory method;

The Beanfactoryaware//setbeanfactory (beanfactory beanfactory) interface causes the bean to be initialized to obtain a beanfactory resource for operation. There are similar applicationcontextaware ....

 Public InterfaceBeanpostprocessor {/**property values have been set to complete,* Apply This beanpostprocessor to the given new beans instance <i>before</i> any bean * Initializa tion callbacks (like Initializingbean ' s <code>afterPropertiesSet</code> * or a custom init-method).     The bean would already is populated with property values.     * The returned bean instance may be a wrapper around the original. * @paramBean The new Bean instance *@paramBeanname The name of the bean *@returnThe bean instance to use, either the original or a wrapped one; if * <CODE>NULL</CODE>, no subsequent Beanpostprocessors'll be invoked *@throwsOrg.springframework.beans.BeansException in case of errors *@seeOrg.springframework.beans.factory.initializingbean#afterpropertiesset*/Object Postprocessbeforeinitialization (Object bean, String beanname)throwsbeansexception; /*** Apply This beanpostprocessor to the given new beans instance <i>after</i> any bean * Initializat Ion callbacks (like Initializingbean ' s <code>afterPropertiesSet</code> * or a custom init-method).     The bean would already is populated with property values.     * The returned bean instance may be a wrapper around the original.  * <p>in Case of a factorybean, this callback'll be invoked for both the Factorybean * instance and the objects Created by the Factorybean (as of Spring 2.0). The * Post-processor can decide whether to apply to either the Factorybean or created * objects or both through CO     Rresponding <code>bean instanceof factorybean</code> checks. * <p>this callback would also be invoked after a short-circuiting triggered by a * {@linkInstantiationawarebeanpostprocessor#postprocessbeforeinstantiation} method, * In contrast to all other BEANPOSTPR     Ocessor callbacks. * @paramBean The new Bean instance *@paramBeanname The name of the bean *@returnThe bean instance to use, either the original or a wrapped one; if * <CODE>NULL</CODE>, no subsequent Beanpostprocessors'll be invoked *@throwsOrg.springframework.beans.BeansException in case of errors *@seeOrg.springframework.beans.factory.initializingbean#afterpropertiesset *@seeOrg.springframework.beans.factory.FactoryBean*/Object Postprocessafterinitialization (Object bean, String beanname)throwsbeansexception;}

/** has completed the property padding (completion of the Afterpropertiesset () Call of the Initializingbean interface, and if the Init-method method is specified, the call has also been completed (after: ()))
   
* Initialize The given bean instance, applying factory callbacks * as well as init methods and Bean post proc Essors. * <p>called from {@link#createBean} for traditionally defined beans, * and from {@link#initializeBean} for existing bean instances. * @paramBeanname The bean name in the factory (for debugging purposes) *@paramBean The new bean instance we may need to initialize *@paramMBD The bean definition that the bean is created with * (can also is <code>null</code>, if given an Existing Bean instance) *@returnThe initialized Bean instance (potentially wrapped) *@seeBeannameaware *@seeBeanclassloaderaware *@seeBeanfactoryaware *@see#applyBeanPostProcessorsBeforeInitialization *@see#invokeInitMethods *@see#applyBeanPostProcessorsAfterInitialization*/ protectedObject Initializebean (FinalString Beanname,FinalObject Bean, rootbeandefinition mbd) { if(System.getsecuritymanager ()! =NULL) {accesscontroller.doprivileged (NewPrivilegedaction<object>() { PublicObject Run () {invokeawaremethods (beanname, Bean); return NULL; }}, Getaccesscontrolcontext ()); } Else{invokeawaremethods (beanname, Bean); } Object Wrappedbean=Bean; if(mbd = =NULL|| !mbd.issynthetic ()) {Wrappedbean=applybeanpostprocessorsbeforeinitialization (Wrappedbean, beanname);//Call Beanpostprocessor before method} Try{invokeinitmethods (Beanname, Wrappedbean, mbd); } Catch(Throwable ex) {Throw Newbeancreationexception ((mbd!=NULL? Mbd.getresourcedescription ():NULL), Beanname,"Invocation of Init method failed", ex); } if(mbd = =NULL|| !mbd.issynthetic ()) {Wrappedbean=applybeanpostprocessorsafterinitialization (Wrappedbean, beanname);//Call
The After method of Beanpostprocessor
return Wrappedbean;}

beanfactory bf = new Xmlbeanfactory (New Classpathresource ("Spring.xml"));

The BF simply saves some beandeinationmap and does not instantiate immediately, requiring subsequent calls to Getbean to initialize:

ApplicationContext AC2 = new Classpathxmlapplicationcontext ("Spring.xml");

AC2 will add the bean Spring.xml defined in the factory to the cache as soon as it is instantiated.

Examples with ApplicationContext:

Spring.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" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:      Mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema/beans      Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/context      Http://www.springframework.org/schema/context/spring-context-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd Http://www.springframework.org/schema/tx HTTP://WW W.springframework.org/schema/tx/spring-tx-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springfra Mework.org/schema/mvc/spring-mvc-3.2.xsd     "> <alias name=" User "alias=" testxx "/> <bean id=" Father "abstract=" true "> <property      Name= "local" value= "Us"/> </bean> <bean id= "user" class= "com.donghua.bean.User" parent= "Father" > <property name= "name" value= "Allen"/> <property name= "age" value= "6"/> </bean> < Bean id= "User3" class= "Com.donghua.bean.User3" init-method= "Myinit" destroy-method= "destroy" > <property name= " Name "value=" Allen3 "/> <property name=" age "value=" all "/> </bean> <bean id=" Factory "class = "Com.donghua.bean.MyBeanFactory"/></beans>

User3:

Package Com.donghua.bean;import Org.springframework.beans.beansexception;import Org.springframework.beans.factory.beanfactory;import Org.springframework.beans.factory.beanfactoryaware;import Org.springframework.beans.factory.initializingbean;import Org.springframework.beans.factory.config.beanpostprocessor;import Org.springframework.beans.factory.config.destructionawarebeanpostprocessor;public class User3 Implements Beanpostprocessor, Initializingbean, Destructionawarebeanpostprocessor,beanfactoryaware{beanfactory BeanFactory; private string Name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} public void Myinit () {System.out.println ("This is my init ..." +this.getage ());} @Overridepublic String toString () {return "User [name=" + name + ", age=" + Age + "]";} @Overridepublic Object Postprocessbeforeinitialization (Object bean, String beanname) throws Beansexception {//TODO auto-generated method StubSystem.out.println ("This is the post before ..."); return bean;}. @Overridepublic Object Postprocessafterinitialization (Object bean, String beanname) throws Beansexception {//TODO Auto-generated method StubSystem.out.println ("This was the post after ................"); return bean; @Overridepublic void Afterpropertiesset () throws Exception {//TODO auto-generated method StubSystem.out.println ("This Is Initializingbean method ... "+" (called by before Init method, after set property values). " +this.getage ());} @Overridepublic void Postprocessbeforedestruction (Object bean, String beanname) throws Beansexception {//TODO Auto-generated method StubSystem.out.println ("This was destructionawarebeanpostprocessor, called when Destroy Bean ...") ;} public void Destroy () {System.out.println ("This is Destroy method ..."); @Overridepublic void Setbeanfactory (Beanfactory beanfactory) throws Beansexception {//TODO auto-generated method Stubthis.beanfactory = BeAnfactory;} public void GetUser2 () {User U = (user) Beanfactory.getbean ("User"); System.out.println (u.tostring () + "This is user2 ...");}

 

Package Com.donghua.test;import Org.springframework.beans.factory.beanfactory;import Org.springframework.beans.factory.xml.xmlbeanfactory;import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springframework.core.io.classpathresource;import Com.donghua.anotation.user2;import Com.donghua.bean.mybeanfactory;import Com.donghua.bean.user;import Com.donghua.bean.user3;public class Test {public static void Main (string[] args) {ApplicationContext AC2 = new Classpathxmlapplicationcontext ("Spring.xml"); User3 U3 = (User3) ac2.getbean ("User3"); System.out.println (U3); U3.getuser2 ();((classpathxmlapplicationcontext) AC2). Close ();  }}

Output order:

This is Initializingbean method ... (Called by before Init method, after set property values).//initializingbean
This is my init ..... //init-method
This is the post before ....//beanpostprocesser.--The
This was the post after ..... .....
This is the post before ..... .....
This was the post after ..... .....
User [Name=allen3, age=61]
User [Name=allen, age=6] This is user2 ...
This was destructionawarebeanpostprocessor, called when destroy Bean ...//Destructionawa Rebeanpostprocessor
This was destructionawarebeanpostprocessor, called when Destroy Bean ...
This is Destroy method ....//destory method

 

Important interfaces commonly used in spring

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.