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);
}
}