Add Bean Programmatically to Spring Web App Context
Solution 1:
Here is a simple code:
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean);
Solution 2:
In Spring 3.0 you can make your bean implement BeanDefinitionRegistryPostProcessor
and add new beans via BeanDefinitionRegistry
.
In previous versions of Spring you can do the same thing in BeanFactoryPostProcessor
(though you need to cast BeanFactory
to BeanDefinitionRegistry
, which may fail).