在JUnit测试期间,我想从多个线程测试我的bean singleton
和prototype
。
我正在使用这个结构:
// to test singleton
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext.getAutowireCapableBeanFactory();
registry.getBeanDefinition("myBean").setScope("singleton");
// it's called from separate thread
MyBean myBean = applicationContext.getBean("myBean");
现在是原型
// to test prototype
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext.getAutowireCapableBeanFactory();
registry.getBeanDefinition("myBean").setScope("prototype");
// it's called from separate thread
MyBean myBean = applicationContext.getBean("myBean");
但它似乎没有效果,并且使用applicationContext.xml
中定义的bean范围。
如何在没有多个applicationContext
s的任何技巧的情况下动态更改bean的范围?
答案 0 :(得分:2)
这样做:
// to test singleton
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext.getAutowireCapableBeanFactory();
// registry.getBeanDefinition("myBean").setScope("prototype"); <-- removed this
BeanDefinition def = registry.getBeanDefinition("myBean");
def.setScope("prototype"); // or `singleton`
registry.registerBeanDefinition("myBean", def);
// it's called from separate thread
MyBean myBean = applicationContext.getBean("myBean");
只需在注册表中重新注册bean定义即可。