Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject a bean into an ApplicationContext before it loads from a file?

Tags:

java

spring

I have a FileSystemXmlApplicationContext and I would like the beans defined in the XML to take as a constructor argument a bean which is not declared in Spring

For example, I would like to do:

<bean class="some.MyClass">
    <constructor-arg ref="myBean" />
</bean>

So I could imagine doing this via something like:

Object myBean = ...
context = new FileSystemXmlApplicationContext(xmlFile);
context.addBean("myBean", myBean); //add myBean before processing
context.refresh();

Except that there is no such method :-( does anyone know how I can achieve this?

like image 858
oxbow_lakes Avatar asked Jul 10 '09 14:07

oxbow_lakes


2 Answers

How about programmatically creating an empty parent context first, registering your object as a singleton with that context's BeanFactory using the fact that getBeanFactory returns an implementation of SingletonBeanRegistry.

parentContext = new ClassPathXmlApplicationContext();
parentContext.refresh(); //THIS IS REQUIRED
parentContext.getBeanFactory().registerSingleton("myBean", myBean)

Then specify this context as a parent to your "real" context The beans in the child context will then be able to refer to the bean in the parent.

String[] fs = new String[] { "/path/to/myfile.xml" } 
appContext = new FileSystemXmlApplicationContext(fs, parentContext);
like image 151
skaffman Avatar answered Sep 21 '22 18:09

skaffman


As I had trouble solving this with an AnnotationConfigApplicationContext, I found the following alternative:

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("customBean", new CustomBean());
context = new AnnotationConfigApplicationContext(beanFactory);
context.register(ContextConfiguration.class);
context.refresh();
like image 23
Ben Romberg Avatar answered Sep 20 '22 18:09

Ben Romberg