So, the title is pretty straightforward. I have a handler class DynamicBeanHandler
which implements BeanDefinitionRegistryPostProcessor
interface provided by spring. In this class I'm adding multiple SCOPE_SINGLETON
beans which have bean class set as MyDynamicBean
as follows-
GenericBeanDefinition myBeanDefinition = new GenericBeanDefinition();
myBeanDefinition.setBeanClass(MyDynamicBean.class);
myBeanDefinition.setScope(SCOPE_SINGLETON);
myBeanDefinition.setPropertyValues(getMutableProperties(dynamicPropertyPrefix));
registry.registerBeanDefinition(dynamicBeanId, myBeanDefinition);
The method getMutableProperties()
returns an object of MutablePropertyValues
.
Later on, I do SpringUtil.getBean(dynamicBeanId)
to fetch the required MyDynamicBean
instance where SpringUtil
class implements ApplicationContextAware
. All this works great. The problem comes when I want to remove one of these instances and add a new instance later on where I don't have the registry instance. Can anyone please help me find a way to do this?
Following is the code for class SpringUtil
-
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) {
return applicationContext.getBean(beanId);
}
public static <T> T getBean(String beanId, Class<T> beanClass) {
return applicationContext.getBean(beanId, beanClass);
}
}
You can make use of BeanDefinitionRegistry
(look here for API) to remove or register the beans dynamically.
So, in your SpringUtil
class, you can add the below method to remove the existing bean definition using removeBeanDefinition()
and then add a new bean definition by using registerBeanDefinition()
.
public void removeExistingAndAddNewBean(String beanId) {
AutowireCapableBeanFactory factory =
applicationContext.getAutowireCapableBeanFactory();
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;
registry.removeBeanDefinition(beanId);
//create newBeanObj through GenericBeanDefinition
registry.registerBeanDefinition(beanId, newBeanObj);
}
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