To preprocess a managed bean using the Beanpostprocessor interface
Sometimes, we want to do some preprocessing of the bean before the spring IOC container initializes the managed bean, after the property is set, or to release the resource itself before the container destroys the managed bean. So how to achieve it? Spring IOC provides us with a variety of ways to implement preprocessing and reprocessing for managed beans.
The Beanpostprocessors interface is defined in spring, and the code is as follows:
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean,String BeanName)throws BeansException;
Object postProcessAfterInitialization(Object bean,String BeanName)throws BeansException;
}
If an implementation class for this interface is registered to a container, each managed bean of the container obtains a callback to the interface implementation class before invoking the initialization method. When a container invokes a method defined by an interface, the instance and first name of the managed bean are passed through the parameter to the method, which is returned to the container by the return value of the method after processing. Based on this principle, we can easily customize a managed Bean.
As mentioned above, to use the beanpostprocessor callback, you must first register the class that implements the interface in the container, so how do you register? Beanfactory and ApplicationContext containers are not registered the same way: if you use Beanfactory, you must display a call to its addbeanpostprocessor () method for registration, The parameter is an instance of the Beanpostprocessor implementation class, and if it is using ApplicationContext, the container automatically looks for the bean that implements the Beanpostprocessor interface in the configuration file, and then registers automatically, All we have to do is configure a beanpostprocessor to implement the class bean.
Note that if we use more than one Beanpostprocessor implementation class, how do we determine the order of processing? In fact, as long as the implementation of the ordered interface, set the Order property can easily determine the different implementation of the processing sequence of classes.
Routine 3.5 shows how to use the Beanpostprocessor callback interface. After you create the Java project, add the spring development capability to create the Ioc.test package. Then create a bean with the name animal, add name, age member, and speak () method. The code is as follows:
package ioc.test;
public class Animal {
private String name;
private int age;
public String speak(){
return "我的名字是:"+this.name+",年龄是:"+this.age+"! \n";
}
//Geter和Seter省略
}