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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With