Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set a specific bean object - Spring DI

In my program I need to programmatically configure an ApplicationContext. Specifically, I have a reference to an instance of MyClass and I want to define it as a new bean called "xxyy".

public void f(MyClass mc, ApplicationContext ac) {
  // define mc as the "xxyy" bean on ac ???
  ...
  ...

  // Now retrieve that bean
  MyClass bean = (MyClass) ac.getBean("xxyy");

  // It should be the exact same object as mc
  Assert.assertSame(mc, bean); 
}

The BeanDefinition API let's me specify the class of the new bean, so it does not work for me since I want to specify the instance. I managed to find a solution but it took two additional factory beans which seems like too much code for such an eartly purpose.

Is there a standard API that addresses my needs?

like image 448
Itay Maman Avatar asked Jul 07 '09 13:07

Itay Maman


People also ask

How do I specify a bean to Autowire?

Using the @Qualifier annotation you can specify which bean you want to autowire. Hope this helps. In my case there's only one bean of MyService . beanA and beanB names refer to BaseBean implementations.

How do you set a Spring bean?

There are several ways to configure beans in a Spring container. Firstly, we can declare them using XML configuration. We can also declare beans using the @Bean annotation in a configuration class. Finally, we can mark the class with one of the annotations from the org.


1 Answers

You need to jump through a few hoops to do this. The first step is to obtain a reference to the context's underlying BeanFactory implementation. This is only possible if your context implements ConfigurableApplicationContext, which most of the standard ones do. You can then register your instance as a singleton in that bean factory:

ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
beanRegistry.registerSingleton("xxyy", bean);

You can "insert" any object into the context like this.

like image 51
skaffman Avatar answered Sep 29 '22 22:09

skaffman