Extension points for Spring container

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/kkdelta/article/details/5488430

After parsing the configuration file, spring calls some of the callback methods that developers of spring can use to provide these callback methods to extend the spring container.
1. By implementing Beanpostprocessor to accomplish some customization of some beans, Beanpostprocessor defines two methods, Postprocessbeforeinitialization (an Object bean, String beanname) and postprocessafterinitialization (Object bean, String beanname). Postprocessbeforeinitialization the dependency registration (the assignment of the member variable specified by the property) is completed after spring has been initialized for the bean. But container has not yet invoked the declared initialization method (such as Afterpropertiesset, Init-method) Called before. Postprocessafterinitialization will invoke the declared initialization method (such as Afterpropertiesset) in container is called later. If you need to have multiple classes that implement Beanpostprocessor, you can control the order in which the callback of these classes are called by implementing the ordered interface. This bean's post-processor is generally used to check if the bean implements an interface, or if the bean is packaged into some proxy,spring AOP some framework class is implemented Beanpostprocessor.

Cases:

 Public classMybeanpostprocessorImplementsBeanpostprocessor, Invocationhandler {PrivateObject proxyobj;  Publicmybeanpostprocessor () {} Publicmybeanpostprocessor (Object obj) {proxyobj=obj; }     PublicObject Postprocessbeforeinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Postprocessbeforeinitialization Bean" +Beanname+ "' Created:" +bean.tostring ()); if(BeaninstanceofIntf) {Class CLS=Bean.getclass (); returnproxy.newproxyinstance (Cls.getclassloader (), CLS. Getinterfaces (),Newmybeanpostprocessor (Bean)); } Else {            returnBean; }    }     PublicObject Postprocessafterinitialization (Object bean, String beanname)throwsbeansexception {System.out.println ("Postprocessafterinitialization Bean" +Beanname+ "' Created:" +bean.tostring ()); returnBean; } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Proxy is" +Proxy.getclass (). GetName ()); System.out.println ("Before calling" +method); if(Args! =NULL) {             for(inti = 0; i < args.length; i++) {System.out.println (Args[i]+ ""); }} Object o=Method.invoke (proxyobj, args); System.out.println ("After calling" +method); returno; }} Public InterfaceIntf { PublicString TestFunc ();} Public classIntfbeanImplementsIntf {PrivateString strval = "Default Value"; @Override PublicString TestFunc () {//TODO auto-generated Method Stub        returnStrval; }}<bean id= "Intfbean"class= "Com.test.spring.extent.IntfBean"/><beanclass= "Com.test.spring.extent.MyBeanPostProcessor"/>

Note that the class that implements Beanpostprocessor here is called for the other beans in the IOC container, not for beanpostprocessor itself and other beanpostprocessor calls. If in the configuration file only beanpostprocessor itself, no other beans, such as only <beanclass= "Com.test.spring.extent.MyBeanPostProcessor"/> Configuration, Postprocessbeforeinitialization and postprocessafterinitialization are not called. Beanpostprocessor will be initialized by the container before the normal bean is initialized. .
Calling code:
Intf Intfbean = (Intf) ctx.getbean ("Intfbean");
System.out.println (Intfbean.testfunc ());
In this way, mybeanpostprocessor will wrap the bean that implements the intf interface into a proxy.

2. Manipulate the configuration file by implementing the Beanfactorypostprocessor interface to make the configuration metadata special. The Spring IOC container allows Beanfactorypostprocessor to read the configuration metadata before the container actually instantiates any other beans, and it is possible to modify it. Spring's own propertyplaceholderconfigurer implements this interface by using placeholders in the XML configuration file, The propertyplaceholderconfigurer is replaced by reading the value from another property file.
Example: Replace ${test with read value from Ext.properties. Prop1},${test. PROP2}.

 <bean  class  = " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> <property name=" Locations "value=" Classpath:conf/ext.properties "/> <property name=" Properties "> <value>test. Prop3=inside property</value> </property> </bean> <bean id= "Propreplacebean" class  = "Com.test.spring.extent.PropReplaceBean" > <property name= "strval" value= "${te St. PROP1} "/> <property name=" intval "value=" ${test. PROP2} "/> <property name=" Insideprop "value=" ${test. PROP3} "/> </bean> 

Usually the more useful scenario is the database URL, user name, password configuration, can also be used to dynamically specify the class name of a bean, the XML file and the property file maintenance easier.
<bean id= "Xxxbean" class= "${com.xxx.class}"/>
Custom Beanfactorypostprocessor can change the order of callback by implementing the ordered interface. The Configurablelistablebeanfactory beanfactory in the callback method provides metadata for the configuration file. (* A confused question is: Propertyplaceholderconfigurer's order was integer.max_value, but it found that it was executed before the processor, which had its own defined order-1.)

<beanclass= "Com.test.spring.extent.MyBeanFactoryPostProcessor"/> Public classMybeanfactorypostprocessorImplementsBeanfactorypostprocessor, Ordered {Private intOrder =-1;  Public voidSetorder (intorder) {         This. Order =order; }     Public intGetOrder () {return  This. Order; } @Override Public voidpostprocessbeanfactory (configurablelistablebeanfactory beanfactory)throwsbeansexception {beandefinition beandefinition=beanfactory. Getbeandefinition ("Propreplacebean"); Mutablepropertyvalues PVs=beandefinition.getpropertyvalues (); Propertyvalue[] Pvarray=pvs.getpropertyvalues ();  for(PropertyValue pv:pvarray) {System.out.println (Pv.getname ()+ "  " +Pv.getvalue (). GetClass ()); }    }}

Spring detects that Beanpostprocessor and beanfactorypostprocessor are automatically called by the container callback methods, without having to invoke them actively in the code.

Extension points for Spring container

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.