Bean后置处理器接口,在初始化方法前后执行,允许对新建的Bean实例进行自定义修改,如检查标记接口或者包装为代理类。
源码
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
import org.springframework.lang.Nullable;
public interface BeanPostProcessor {
/**
* 在属性填充完成之后,初始化方法(afterPropertiesSet 或者 @PostConstruct)之前执行。
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* 初始化方法之后之前执行。
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
执行时机
在Bean实例创建并完成属性填充之后,调用AbstractAutowireCapableBeanFactory的initializeBean方法初始化Bean。在初始化前后分别执行了 postProcessBeforeInitialization 和 postProcessAfterInitialization 方法。
代码实践
新建一个BeanPostProcessor实例
/**
* 对所有Spring管理的Bean都有效
* */
@Slf4j
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
log.info("执行 BeanPostProcessor.postProcessBeforeInitialization 方法, beanName=>{}", bean, beanName);
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
log.info("执行 BeanPostProcessor.postProcessAfterInitialization 方法, beanName=>{}", bean, beanName);
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
新建一个Spring Component类,并实现依赖注入和初始化方法
@Slf4j
@Component
public class BeanPostProcessorDemo implements InitializingBean {
private AnotherComponent anotherComponent;
@Autowired
public void setAnotherComponent(AnotherComponent anotherComponent) {
log.info("执行依赖注入");
this.anotherComponent = anotherComponent;
}
@PostConstruct
public void init(){
log.info("执行 @PostConstruct 标注的方法");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("执行 InitializingBean.afterPropertiesSet 方法");
}
}
运行结果
执行顺序为:依赖注入 > postProcessBeforeInitialization > @PostConstruct > afterPropertiesSet > postProcessAfterInitialization
注:BeanPostProcessor默认是会对整个Spring容器中所有的bean进行处理。