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); }
You must call registerBeanDefinition on the bean definition registry to register a new bean definition. This registerBeanDefinition takes the bean name and definition as input. You can use the BeanDefinitionBuilder to create a BeanDefinition programmatically (introduced in Spring 2.0). bdr.
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
Here is a simple code:
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean);
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