java – 在从文件加载之前,如何将Bean注入到ApplicationContext中?

我有一个FileSystemXmlApplicationContext,我希望在 XML中定义的bean作为一个构造函数参数,一个未在 Spring中声明的bean

例如,我想做:

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

所以我可以想像这样做:

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

除了没有这样的方法:-(有没有人知道我能如何实现?

解决方法

首先如何以编程方式创建一个空的父上下文,使用getbeanfactory返回一个SingletonBeanRegistry实现的事实,使用该上下文的beanfactory将对象注册为单例.
parentContext = new ClasspathXmlApplicationContext();
parentContext.refresh(); //THIS IS required
parentContext.getbeanfactory().registerSingleton("myBean",myBean)

然后将此上下文指定为“真实”上下文的父级,然后,子上下文中的bean将可以引用父进程中的bean.

String[] fs = new String[] { "/path/to/myfile.xml" } 
appContext = new FileSystemXmlApplicationContext(fs,parentContext);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...