在JUnit测试期间动态更改bean范围

时间:2013-11-23 13:24:32

标签: java spring unit-testing javabeans

在JUnit测试期间,我想从多个线程测试我的bean singletonprototype

我正在使用这个结构:

    // 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的范围?

1 个答案:

答案 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定义即可。