初始化Bean的扩展InitializingBean和BeanPostProcessor
Bean的扩展
- 这两个接口都是可以在Bean创建过程中进行拦截,那么他们有什么区别呢?
示例如下:
InitializingBean 接口实现类:
@Component
public class MyInitBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean afterPropertiesSet");
}
}
BeanPostProcessor 接口实现类:
@Component
public class MyBeanProcess implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof UserService){
System.out.println("UserService");
}
System.out.println("BeanPostProcessor postProcessBeforeInitialization");
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor postProcessAfterInitialization");
return null;
}
}
启动项目,运行结果如下:
结果分析:
InitializingBean 接口实现类只执行了一次,而BeanPostProcessor接口实现类执行了多次。
结论:
说明InitializingBean可以对自身的实现类的这个Bean进行拦截,而BeanPostProcessor是对所有Bean进行拦截。