BeanPostProcessor:回调机制,在 bean 的初始化前后做一些额外的处理,扩展功能。
可以配置多个 BeanPostProcessor 实例,并且可以通过实现Ordered接口,设置order属性来控制这些BeanPostProcessor实例的运行顺序。
//原接口
public interface BeanPostProcessor {
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
//编写后置处理器,对每个bean的创建都会生效
@Component
public class AnimalBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("拦截到Bean的初始化之前:" + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("拦截到Bean的初始化之后:" + beanName);
return bean;
}
}
通过后置处理器修改bean的属性
@Component
public class CatBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
Cat cat = (Cat) bean;
System.out.println("初始化之前,cat的name为:" + cat.getName());
cat.setName("zhangsan");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Cat) {
Cat cat = (Cat) bean;
System.out.println("初始化之后,cat的name为:" + cat.getName());
}
return bean;
}
}
bean的初始化流程:
对于factorybean,后置处理器会在factorybean创建时执行Before和after方法,在用factorybean去getbean时,执行after方法。