Archer
Archer

Reputation: 5147

Dynamically changing bean scope during JUnit testing

During JUnit testing I'd like to test my bean from multiple threads as singleton and prototype.

I'm using this construct:

    // to test singleton
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext.getAutowireCapableBeanFactory();                                                                                                                                                                                                          
    registry.getBeanDefinition("myBean").setScope("singleton");

    // it's called from separate thread
    MyBean myBean = applicationContext.getBean("myBean");

Now for prototype

    // to test prototype
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry)applicationContext.getAutowireCapableBeanFactory();                                                                                                                                                                                                          
    registry.getBeanDefinition("myBean").setScope("prototype");

    // it's called from separate thread
    MyBean myBean = applicationContext.getBean("myBean");

But it seems it has no effect and bean scope defined in applicationContext.xml is used.

How to dynamically change bean's scope without any tricks with multiple applicationContexts?

Upvotes: 3

Views: 1850

Answers (1)

Archer
Archer

Reputation: 5147

Done this that way:

    // 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");

Just re-registering bean definition in registry does the trick.

Upvotes: 2

Related Questions