Add Bean Programmatically to Spring Web App Context
Here is a simple code:
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean);
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).