BeanFactoryPostProcessor插手spring bean工厂对bean的定义
1、通过实现BeanFactoryPostProcessor接口,重写postProcessBeanFactory方法,可以获取到类的BeanDefinition对象,通过BeanDefinition对象插手bean的定义。(实现类要交给spring管理才可以生效)
例:将IndexDao对象从singleton改为prototype
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition indexDao = beanFactory.getBeanDefinition("indexDao");
indexDao.setScope("prototype");
}
}
@Component
public class IndexDao implements Dao {
@Override
public void query(){
System.out.println("index");
}
}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext();
app.register(Appconfig.class);
app.refresh();
Dao bean = app.getBean(IndexDao.class);
Dao bean1 = app.getBean(IndexDao.class);
System.out.println(bean.hashCode()+"--"+bean1.hashCode());
}
}
执行结果: