BeanPostProcessor允许在调用初始化方法前后对 Bean 进行额外的处理。
BeanPostProcessor源码
public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }
BeanPostProcessor定义了两个方法postProcessBeforeInitialization(Object bean, String beanName) 与 postProcessAfterInitialization(Object bean, String beanName)。bean为需要操作的bean对象,beanName为该对象的名字。
执行顺序
postProcessorBeforeInitailization() 方法是在bean实例化,依赖注入之后调用,初始化方法之前。
postProcessorAfterInitailization()方法是初始化方法之后调用。
如示例
public class HelloSpring { public HelloSpring() {System.out.println("HelloSpring Constructor");} private String message; public void setMessage(String message) { this.message = message; System.out.println("Message was injected"); } public String getMessage() {return message;} // 初始化方法 public void init() {System.out.println("Bean is going through inti");} }
BeanPostProcessor实现
public class InitHelloSpring implements BeanPostProcessor{ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before initialization: " + beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("After initialization: " + beanName); return bean; } }
public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); } }
执行结果如下:
// bean的实例化与依赖注入 HelloSpring Constructor Message was injected // 执行postProcessorBeforeInitailization() 方法 Before initialization: helloSpring // 执行bean的初始化方法 Bean is going through inti // 执行postProcessorAfterInitailization()方法 After initialization: helloSpring
postProcessBeforeInitialization() 与 postProcessAfterInitialization()方法的返回值
这两个方法返回一个Object对象,该对象会更新Spring容器其中原有的bean。
如上例中,Spring容器中注入的是HelloSpring类型的bean,bean的名字为helloSpring,如果 postProcessBeforeInitialization() 与 postProcessAfterInitialization()返回的不是原有的bean,则原有的会被替换。
如
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Before initialization: " + beanName); return new Object(); }
postProcessBeforeInitialization() 方法返回的是Object对象,该对象则会取代Spring容器中名为helloSpring的bean。
public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); Object obj = context.getBean("helloSpring"); System.out.println(obj instanceof HelloSpring); }
执行结果为false。