首页 > 解决方案 > 为什么 Spring 的 PathMatchingResourcePatternResolver 没有匹配“*”?

问题描述

我正在尝试从 zip 文件中获取属性文件。我需要使用通配符,因为我想匹配“my.properties”或“my_en.properties”。我创建一个ResourcePatternResolver这样的:

ClassLoader loader = MyClass.class.getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader);

当我尝试不使用通配符检索“my.properties”文件时,我成功了:

resolver.getResource("file:C:/somePath/a.zip/META-INF/my.properties").exists()

返回true。但是,如果我在文件名中添加通配符,则会失败,例如,

resolver.getResource("file:C:/somePath/a.zip/META-INF/my*.properties").exists()

返回false。我可以做些什么来匹配和检索这两个文件?我正在尝试在 Tomcat 中的 webapp 中执行此操作。

标签: spring

解决方案


文档对此并不清楚,但是该getResource方法在内部不使用 PathMatcher 来解析资源(这意味着不允许使用通配符),getResources(String locationPattern)而是尝试。

例如 :

Resource[] resources = resolver.getResources("file:C:/somePath/a.zip/META-INF/my*.properties");

for(Resource resource : resources) {
  // do something for each resource found
}

推荐阅读