spring中如何引用另一个xml文件的bean
我有一个在 xml 文件中定义的 Spring bean。我想从另一个 xml 文件引用它。我该怎么办呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我有一个在 xml 文件中定义的 Spring bean。我想从另一个 xml 文件引用它。我该怎么办呢?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
您有几个选项:
导入
包含在
ApplicationContext
构造中创建时将这两个文件都作为
ApplicationContext
的一部分 =>那么不需要导入。例如,如果您在测试期间需要它:
如果它是一个网络应用程序,您可以在
web.xml
中进行:如果它是一个独立的应用程序、库等...您可以加载您的
ApplicationContext
为:You have a couple of options:
Import
Include in the
ApplicationContext
ConstructionMake both files a part of your
ApplicationContext
when you create it => then no import is needed.For example if you need it during testing:
In case it is a web app, you'd do it in
web.xml
:If it is a stand alone app, library, etc.. you would load your
ApplicationContext
as:只需使用
导入定义 bean 的 xml,您就可以使用 bean 定义。您可以在
resource
属性中使用classpath:
:请参阅 Spring 参考的本章
Just import the xml defining the bean with
<import resource="otherXml.xml">
and you will be able to use the bean definition.You can use
classpath:
in theresource
attribute:See the "3.18. Importing Bean Definitions from One File Into Another" in this chapter of the Spring Reference
引用它就像引用同一个 XML 文件中的 bean 一样。如果 spring 上下文由多个 XML 文件组成,则所有 bean 都是同一上下文的一部分,因此共享唯一的名称空间。
You reference it exactly as you would reference a bean in the same XML file. If a spring context is composed of several XML files, all the beans are part of the same context, and thus share a unique namespace.
或者,如果您只是将 beans 重构为多个文件以防止单个 xml 文件变大,只需从其当前文件夹中引用它即可:
Or if you are just refactoring beans into several files to keep the single xml file from growing to large, simply reference it from its current folder:
您也可以通过在代码中加载多个 Spring bean 配置文件来实现此目的:
将所有 spring xml 文件放在项目类路径下:
但是,上述实现缺乏组织且容易出错,更好的方法应该组织所有 Spring bean配置文件合并到单个 XML 文件中。例如,创建一个
Spring-All-Module.xml
文件,并像这样导入整个 Spring bean 文件:您可以像这样加载单个 xml 文件:
现在
在 Spring3 中,替代解决方案是使用 JavaConfig @Import。
You may also go about this by loading multiple Spring bean configuration files in the code :
Put all spring xml files under project classpath:
However, the above implementation is a lack of organizing and error prone, the better way should be organized all your Spring bean configuration files into a single XML file. For example, create a
Spring-All-Module.xml
file, and import the entire Spring bean files like this :Now you can load a single xml file like this :
Note
In Spring3, the alternative solution is using JavaConfig @Import.
tolitius 提供的答案非常详细。
只是针对 Peter Butkovic 提到的问题
我遇到了同样的问题,并通过在同一标签中用“,”分割两条路径来解决。
它会看起来像这样
Answer provided by tolitius is very detailed.
Just for the problem mentioned by Peter Butkovic
I met the same problem and solved by spliting two paths with "," in the same tag.
It will look like this