Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Bean Programmatically to Spring Web App Context

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); } 
like image 416
user146714 Avatar asked Dec 27 '10 18:12

user146714


People also ask

How do I register a bean in Spring context?

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.

Can we use @bean without @configuration?

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


1 Answers

Here is a simple code:

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean); 
like image 152
sndyuk Avatar answered Sep 20 '22 15:09

sndyuk