Java – how to inject beans into ApplicationContext before loading from a file?
•
Java
I have a filesystemxmlapplicationcontext. I want the bean defined in XML as a constructor parameter, a bean that is not declared in spring
For example, I want to do:
<bean class="some.MyClass">
<constructor-arg ref="myBean" />
</bean>
So I can imagine doing this:
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 it?
Solution
First, how to programmatically create an empty parent context, use getbeanfactory to return the fact of a singletonbeanregistry implementation, and use the beanfactory of the context to register the object as a singleton
parentContext = new ClassPathXmlApplicationContext();
parentContext.refresh(); //THIS IS required
parentContext.getbeanfactory().registerSingleton("myBean",myBean)
This context is then specified as the parent of the "real" context, and then beans in the child context can reference beans in the parent process
String[] fs = new String[] { "/path/to/myfile.xml" }
appContext = new FileSystemXmlApplicationContext(fs,parentContext);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
