使用 PathMatchingResourcePatternResolver 获取 WAR 文件中的 src/main/resources 时遇到问题

Trouble using PathMatchingResourcePatternResolver to get src/main/resources in WAR file

我正在使用 Spring 的 PathMatchingResourcePatternResolver 来尝试获取当前位于我的 src/main/resources 目录中的 .jmx 文件列表(JMeter 测试)。这将作为 WAR 文件托管在 AWS 上。

当我在本地工作时,我有这个代码块为我提供了 resources/ 目录中的 .jmx 文件列表,但我知道不能使用我的本地文件路径:

PathMatchingResourcePatternResolver resolver =
                   new PathMatchingResourcePatternResolver(MyClass.class.getClassLoader());
Resource[] resources = resolver.getResources("file:/C:/Users/user.name/repos/my-repo/src/main/resources/dailyTests/*.jmx")

我一直在尝试使用类路径*:这实际上几乎可以工作:

Resource[] resources = resolver.getResources("classpath*:*.jmx");

这将获取我所有的 .jmx 文件,其 URL 如下所示:

file:/C:/Users/user.name/repos/my-repo/target/classes/my_jmeter_test.jmx

但我还需要能够处理资源目录的子目录。当我尝试更具体时,我相信我输入的模式不正确。据我了解,当使用 classpath* 时,您仍然需要在 classpath*: 之后使用根目录,但我不确定应该是什么。

到目前为止我已经试过了

Resource[] resources = resolver.getResources("classpath*:Users/*.jmx");
Resource[] resources = resolver.getResources("classpath*:classes/*.jmx");
Resource[] resources = resolver.getResources("classpath*:WEB-INF/*.jmx");
Resource[] resources = resolver.getResources("classpath*:com/*.jmx");

以及其他许多猜测,所有这些都返回了 0 个资源。似乎当我更具体地一步时,我得到了 0 个资源。

我想我可能误解了我应该如何浏览 WAR 文件,或者可能只是误解了 classpath* 对我的帮助。我完全离开这里了吗?

原来是我对使用 Maven 时 src/main/resources 在 WAR 文件中的位置缺乏了解。 src/main/resources 中的任何文件都将被复制到 WAR 文件的根目录中。 (在选择中注明answer here)。

当使用 Spring 的 PathMatchingResourcePatternResolver 时,classpath* 获取 WAR 的根目录,所以这就是我获取 .jmx 文件的原因:

 Resource[] resources = resolver.getResources("classpath*:*.jmx");

从那里开始,如果我的项目需要嵌套目录中的更多文件,例如 src/main/resources/specialTest。我可以使用:

Resource[] resources = resolver.getResources("classpath*:specialTest/*.jmx");

有一件事我不确定,根据文档:

WARNING: Note that "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like "classpath*:*.xml" will not retrieve files from the root of jar files but rather only from the root of expanded directories.

我认为这意味着我无法从 WAR 文件的根目录中获取文件,但这正是我正在做的。目前看来,当我使用“classpath*:*.jmx”时,我只能从根目录中获取 .jmx 文件,如果我想要更深入的东西,我必须添加一个根目录来启动模式。如果我完全弄清楚这是否正确,我会尝试更新。