- BeanFactoryPostProcessor与BeanPostProcessor执行顺序
- 整体顺序:
- BeanFactoryPostProcessor中 postProcessorBeanFactory
- 实例化Bean。调用bean中的set方法设值。
- BeanFactoryPostProcessor 中的 postProcessorBeforeInitializing
- 初始化Bean。PostConstruct注解的方法执行 --> InitializingBean 接口的 afterPropertiesSet
- BeanFactoryPostProcessor 中的 postProcessorAfterInitializing
/**
* Created by zhaozhebin on 2018/10/14
* <p>
* BeanPostProcessor接口
* (bean的初始化前后,也就是赋值阶段,即调用setter方法)
* <p>
* BeanFactoryPostProcessor(Bean创建之前,读取Bean的元属性,并根据自己的需求对元属性进行改变,比如将Bean的scope从singleton改变为prototype)
* <p>
* 1、BeanFactoryPostProcessor的执行优先级高于BeanPostProcessor
* <p>
* 2、BeanFactoryPostProcessor的postProcessBeanFactory()方法只会执行一次,携带了每个bean的基本信息
*/
@Configuration
@ComponentScan(value = "com.zzb.mytest.TestSpring.TestBeanPostProcessor")
public class TestBeanPostProcessor {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(TestBeanPostProcessor.class);
context.refresh();
TestBean test = context.getBean(TestBean.class);
test.say();
System.out.println(test.getName());
}
@Service
public class A implements BeanPostProcessor {
/**
* 该方法在bean实例化完毕(且已经注入完毕),在afterPropertiesSet或自定义init方法执行之前
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass().equals(TestBean.class)) {
System.out.println("before.....");
}
return bean;
}
/**
* 在afterPropertiesSet或自定义init方法执行之后
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean.getClass().equals(TestBean.class)) {
System.out.println("after.....");
}
return bean;
}
}
}
@Component
public class TestBean implements InitializingBean {
private String name;
public TestBean() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void say() {
System.out.println("zzb say");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("do afterPropertiesSet...");
this.name = "caoxizhaozhebin";
}
@PostConstruct
public void method(){
name="post construct";
System.out.println("post construct");
}
}
@Component
public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("postProcessBeanFactory....---....");
// TestBeanPostProcessor.Test test=beanFactory.getBean(TestBeanPostProcessor.Test.class);
//test.setName("qqqqqq");
BeanDefinition definition=beanFactory.getBeanDefinition("testBean");
MutablePropertyValues values=definition.getPropertyValues();
values.addPropertyValue("name","caoxi");
}
}