Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
Archer Avatar asked Jan 25 '26 03:01

Archer


1 Answers

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.

like image 62
Archer Avatar answered Jan 27 '26 16:01

Archer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!