IOC容器自动识别后置处理器
InitBeforBean 改bean实现BeanFactoryPostProcessor 该接口,
更改 BeanLife bean的属性值和作用域
@Test
public void valueTest(){
ApplicationContext context = new AnnotationConfigApplicationContext("com.huo.SprinBootDmeo");//获取该文件夹下所有的工厂bean
//ApplicationContext context = new AnnotationConfigApplicationContext(BeanLife.class);
BeanLife beanLife = context.getBean(BeanLife.class);
// System.out.println(beanLife.getRemark());
AbstractApplicationContext abstractApplicationContext = (AbstractApplicationContext) context;
abstractApplicationContext.registerShutdownHook();
}
@Component
public class InitBeforBean implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
System.out.println("BeforeInitialization 初始化bean之前========================: " );
BeanDefinition bd = configurableListableBeanFactory.getBeanDefinition("beanLife");
MutablePropertyValues pv = bd.getPropertyValues();
pv.addPropertyValue("remark","属性值改一下");
//bean的作用域也该一下
bd.setScope(BeanDefinition.SCOPE_SINGLETON);
}
}
@Component
public class BeanLife {
private String remark;
public BeanLife(){
System.out.println("构造函数");
}
@PostConstruct
public void init(){
System.out.println("初始化bean后调用");
}
@PreDestroy
public void destroy(){
System.out.println("销毁bean之前调用");
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
运行结果:
BeforeInitialization 初始化bean之前========================:
构造函数
初始化bean后调用
bean销毁后调用