BeanPostProcessor
接口定义了回调方法,让你可以自己实现实例化的逻辑以及依赖解析的逻辑。你可以通过插入一个或者多个BeanPostProcessors
的实现,在Spring容器完成实例化、配置以及初始化之后,实现一些自己设定的逻辑。
你可以配置多个BeanPostProcessor
接口,也可以通过实现Ordered接口提供的order属性来控制这些BeanPostProcessor
接口的执行顺序
BeanPostProcessors
可以对Bean实例进行操作,意味着Spring IoC容器可以实例化一个Bean,然后BeanPostProcessor
开始它们的工作。
ApplicationContext
会自动检测由BeanPostProcessor
接口实现定义的Bean,注册这些bean为后置处理器(BeanPostProcessor),然后通过在容器中创建bean,在适当的时候调用它。
Example
HelloWorld.java
package com.soygrow;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void getMessage() {
System.out.println("Your Message : " + message);
}
public void init() {
System.out.println("init function ...");
}
public void destroy() {
System.out.println("destroy function ...");
}
}
InitHelloWorld.java
package com.soygrow;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class InitHelloWorld implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean;
}
}
MainApp.java
package com.soygrow;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.setMessage("singleton test.");
helloWorld.getMessage();
// 优雅的结束
((ClassPathXmlApplicationContext) context).close();
}
}
Beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloWorld" class="com.soygrow.HelloWorld" init-method="init" destroy-method="destroy">
<property name="message" value="Hello Soygrow!"/>
</bean>
<bean id="initHelloWorld" class="com.soygrow.InitHelloWorld"></bean>
</beans>
如果一切正常,那么运行结果是:
BeforeInitialization : helloWorld
init function ...
AfterInitialization : helloWorld
Your Message : singleton test.
destroy function ...
代码分析
- InitHelloWorld 实现了 BeanPostProcessor 接口,这个类在其他自己定义的bean进行实例化之前和之后都会调用该类中的回调方法
- 在其他bean被实例化之前会调用
postProcessBeforeInitialization
- 在其他bean实例化之后回调用
postProcessAfterInitialization
- 我测试
InitHelloWorld
实例化在其他bean实例化之前。
遇到的问题
没有遇到代码相关的问题,如果有可以在下面评论,我及时回复。