具有不同maven模块的Spring资源解析器

时间:2016-07-02 19:27:43

标签: java spring

因此,对于我们的测试结构,我们目前有一个基本模块,其中我们有一些常见的配置文件等(例如:ds.properties)。现在我正在运行不同模块中的测试,我正在尝试加载所有.properties文件(以获取所有配置)并且我正在使用

(new PathMatchingResourcePatternResolver(getClass().getClassLoader())).getResources("classpath:*.properties")

现在这只是找到alpha.properties(我的模块中的属性文件)。有没有办法在所有模块中获取属性文件?

我已经尝试了一些东西:

(new PathMatchingResourcePatternResolver(getClass().getClassLoader())).getResources("classpath:ds.properties")

返回我想要的ds.properties,但显然不是auth.properties。

(new PathMatchingResourcePatternResolver(getClass().getClassLoader())).getResources("classpath*:*.properties")

再次只有alpha.properties

(new PathMatchingResourcePatternResolver(getClass().getClassLoader())).getResources("classpath*:**/*.properties")

从我不想要的jre中返回alpha.properties和一堆.properties文件。

1 个答案:

答案 0 :(得分:1)

我太懒了,无法在文档中找到引用,但基本上就是这样:

顶级类路径扫描未找到与模式匹配的所有资源。原因写在文档中。

将您的属性文件放在一个包中(对于maven的src / main / resources / somefolder)并调整您的扫描路径,它应该按预期工作。 (classpath *:somefolder / *。properties)

完整性:来自文档

请注意,类路径*:与Ant样式模式结合使用时,只能在模式启动前与至少一个根目录可靠地工作,除非实际目标文件驻留在文件系统中。这意味着像“classpath *:*。xml " will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK’s ClassLoader.getResources()方法这样的模式,它只返回传入的空字符串的文件系统位置(表示潜在的搜索根)。

如果要搜索的根包在多个类路径位置中可用,则不保证具有“classpath:”资源的Ant样式模式可以找到匹配的资源。这是因为资源如

COM / myCompany的/包1 /服务的context.xml 可能只在一个位置,但在路径如

类路径:COM / myCompany的/ ** /服务的context.xml 用于尝试解决它,解析器将解决getResource(“com / mycompany”);返回的(第一个)URL。如果此基本包节点存在于多个类加载器位置中,则实际的最终资源可能不在下面。因此,最好在这种情况下使用具有相同Ant样式模式的“classpath*:”,它将搜索包含根包的所有类路径位置。