如何从一个豆子转移豆子ClassPathXMLApplicationContext
到另一个?
我创建一个这样的上下文
ClassPathXMLApplicationContext myOneContext = new ClassPathXMLApplicationContext("path to my xml bean definitions"); // It loads 10 beans which probably refer each other
ClassPathXMLApplicationContext my2ndContext = new ClassPathXMLApplicationContext("path to my xml bean definitions"); // It loads 2 beans, which probably refer each other
是否可以将所有豆子从my2ndContext
to myOneContext
?
我一直在从 beanFactory 获取myOneContext
并将其内部 bean 工厂设为DefaultSingletonBeanRegistry
并调用registerSingleton
Object beanObject = my2ndContext.getBean("beanName");
DefaultSingletonBeanRegistry lbf =(DefaultSingletonBeanRegistry)myOneContext.getBeanFactory();
lbf.registerSingleton("beanName", beanObject);
这个可以吗?我觉得我正在做一种黑客行为。也不知道我还缺少什么。
另一种选择是将 bean 保留在相同的上下文中,并在 AppContext 及其 bean 工厂之间添加父关系。
myOneContext.setParent(my2ndContext);
DefaultListableBeanFactory lbf = (DefaultListableBeanFactory)myOneContext.getBeanFactory();
lbf.setParentBeanFactory(my2ndContext.getBeanFactory());
这样,来自两个上下文的所有 bean 都可以在myOneContext
但是当我必须销毁my2ndContext
我将 BeanFactory 的父级设置为 null。
DefaultListableBeanFactory lbf = (DefaultListableBeanFactory)myOneContext.getBeanFactory();
lbf.setParentBeanFactory(null); <<< throws exception
因为它不允许改变bean工厂。
From Spring Sourse: AbstractBeanFactory.java
public void setParentBeanFactory(BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
this.parentBeanFactory = parentBeanFactory;
}
我应该选择哪种方式?传输 beans 或建立父关系。哪一个更可取?
Thanks,
Regards,
Vimal