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 方法。
/**
* 对所有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);
}
}
@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进行处理。