如何在从文件加载之前将bean注入ApplicationContext? [英] How can I inject a bean into an ApplicationContext before it loads from a file?

查看:277
本文介绍了如何在从文件加载之前将bean注入ApplicationContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,我想这样做:

<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?

推荐答案

如何首先以编程方式创建一个空的父上下文,将对象注册为具有该上下文的单例 BeanFactory 使用 getBeanFactory 返回 SingletonBeanRegistry 的实现。

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)

然后将此上下文指定为真实上下文的父级然后,子上下文中的bean将能够引用父级中的bean。

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);

这篇关于如何在从文件加载之前将bean注入ApplicationContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆