PathMatchingResourcePatternResolver是Spring框架中用于解析资源路径并匹配资源模式的一个工具类。它常用于在Spring的上下文中加载资源,如:配置文件、类路径下的文件加载等。
PathMatchingResourcePatternResolver是一个Ant模式通配符的Resource查找器,可以用来查找类路径下或者文件系统中的资源获取文件系统文件。
PathMatchingResourcePatternResolver位于spring-core包之中。
一、classpath*:前缀文件读取
- 加载classpath下mapper对应的xml\
public static void main(String[] args) throws IOException {
List<String> list = List.of("classpath*:mapper/mysql/*.xml", "classpath:mapper/oracle/*.xml","classpath:*.properties");
List<Resource> resources = getResources(list);
System.out.println(resources.size());
}
public static List<Resource> getResources(List<String> list) throws IOException {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
List<Resource> resources = new ArrayList<>();
for (String path : list) {
resources.addAll(List.of(resolver.getResources(path)));
}
return resources;
}
上述案例可以读取到classpath下指定路径的所有xml和properties文件。
二、Ant-style样式通配符
当路径包含Ant-style样式通配符,解析器遵循一个更复杂单已定义的过程来尝试解析通配符,如下:
/ WEB-INF/*-context. xml
com/ example/**/applicationContext. xml
file:C:/ some/ path/*-context. xml
classpath:com/ example/**/applicationContext. xml
示例:
public static void main(String[] args) throws IOException {
List<String> list = List.of("META-INF/**/*.lua", "META-INF/spring/**/*.xml");
List<Resource> resources = getResources(list);
System.out.println(resources.size());
}
public static List<Resource> getResources(List<String> list) throws IOException