Add Bean Programmatically to Spring Web App Context

dynamic, java, spring, web-applications

Solution

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).

Problem

Because of a plug-in architecture, I'm trying to add a bean programmatically to my webapp. I have a Spring bean created through the `@Component` annotation, and i am implementing the `ApplicationContextAware` interface. My override function looks like this: ``` @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // this fails this.applicationContext = (GenericWebApplicationContext) applicationContext; } ``` Basically, I can't figure out how to add a bean to the applicationContext object given to setApplicationContext. Can anyone tell me how I am going about this the wrong way? Ok, this is what i ended up with as the solution: ``` @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry bdr) throws BeansException { BeanDefinition definition = new RootBeanDefinition( <My Class>.class); bdr.registerBeanDefinition("<my id>", definition); } ```

Original source