加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:03:07 所属栏目:Java 来源:网络整理
导读:我有一个FileSystemXmlApplicationContext,我希望在 XML中定义的bean作为一个构造函数参数,一个未在 Spring中声明的bean 例如,我想做: bean class="some.MyClass" constructor-arg ref="myBean" //bean 所以我可以想像这样做: Object myBean = ...context
我有一个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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读