views:

900

answers:

3

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?

+1  A: 

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.

skaffman
+1  A: 

you can use this context:

GenericApplicationContext mockContext = new GenericApplicationContext();

which has a

mockContext.getBeanFactory().registerSingleton("name", reference);

and plug it in the real context

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "real-context.xml" }, mockContext);

and the classes are:

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.GenericApplicationContext;
silmx
A: 

My answer is basically the same as the one from silmx, but I wrote a little blog post about this once, Creating Spring Contexts Programmatically. It has a small example that I hope is helpful.

I had a simpler way to inject beans into an active context; however, what it was escapes me at the moment. I think it had something to do with a placeholder bean that is an adapter to your beans interface, but really only a container for it. Configure the adapter/container bean in the context and pull it out at runtime to inject the real implementation... something like that. If I figure out where I did that I will append to this reply.

Good luck.

cjstehno