Spring ApplicationContext 与 Jar 中的多个 XML 文件

2024-01-01

我需要使用当前 Maven 构建中的“main”applicationContext-a.xml 创建一个 ApplicationContext。另一个连接来自另一个 Maven 构建的类,并预设在 Maven 依赖项包含的 jar 中。

这里的想法是:

ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {
                "classpath*:applicationContext-*.xml"});

这应该从类路径加载 applicationContext-a.xml,因为它位于同一个项目中。这有效。

然后应该从 dependency-jar 加载 applicationContext-b.xml。这是行不通的。

注意

"classpath*:applicationContext-*.xml"

只匹配直接类路径中的 XML,jar 中没有任何内容。

我发现了什么:

ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {
                "classpath*:applicationContext-*.xml", "classpath*:applicationContext-b.xml"});

这有效,但前提是我可以明确地告诉 jar 内 xml 的文件名:applicationContext-b.xml

我还需要它来进行集成测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"**/applicationContext*.xml"})
public class TestClass { ... }

最好的想法可能是自定义加载程序? 必须有一种方法可以让这个模式发挥作用......

有一个solution https://stackoverflow.com/questions/6303242/loading-spring-application-context-files-that-are-inside-a-jar-in-classpath前段时间,它的工作方式相反:它只从 jar 中获取 applicationContext.xml 。如果类路径中有另一个文件,则它仅与该文件匹配。


The classpath*:我认为有一个限制不适用于根文件夹下的文件。尝试将文件移动到文件夹下 - 类似于spring/application-a.xml and spring/application-b.xml。然后你就可以有一条路classpath*:/spring/application-*.xml.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring ApplicationContext 与 Jar 中的多个 XML 文件 的相关文章

随机推荐