如何在Quarkus中按匹配模式加载类路径下的资源
在Quarkus中按匹配模式加载类路径资源的解决方案
方法一:使用Quarkus内置ClassPathUtils工具类
Quarkus提供了io.quarkus.runtime.util.ClassPathUtils,专门用于类路径资源扫描,能自动适配dev/prod等不同运行环境,同时解决根目录资源无法识别的问题。
示例代码:
import io.quarkus.runtime.util.ClassPathUtils; import java.util.ArrayList; import java.util.List; import java.nio.file.Path; public class ResourceScanner { public List<Path> getResourcesByPattern(String pattern) { List<Path> matchingResources = new ArrayList<>(); // 扫描所有类路径资源,过滤符合模式的文件 ClassPathUtils.consumeAsPaths(path -> { String fileName = path.getFileName().toString(); // 转换glob模式为正则,比如"*.properties"匹配所有properties文件 if (fileName.matches(pattern.replace("*", ".*"))) { matchingResources.add(path); } }); return matchingResources; } }
关键优势
- 环境适配:自动处理Quarkus dev模式(热部署类加载器)和prod模式(jar/原生镜像)的类路径差异,无需手动处理URL或FileSystem。
- 全路径覆盖:能扫描类路径根目录及子目录下的所有资源,解决
classLoader.getResources("")无法识别根目录的问题。
方法二:基于ClassLoader的增强扫描(兼容标准JVM)
如果需要更底层的实现,可以结合Quarkus类加载器特性,遍历所有类路径条目并扫描:
import java.io.IOException; import java.net.URL; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class ClassPathResourceScanner { public List<Path> scanResources(String pattern) throws IOException { List<Path> resources = new ArrayList<>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 获取所有类路径条目 Enumeration<URL> urls = classLoader.getResources(""); while (urls.hasMoreElements()) { URL url = urls.nextElement(); Path rootPath; // 处理jar文件和目录两种类路径类型 if ("jar".equals(url.getProtocol())) { String jarPath = url.getPath().substring(5).split("!")[0]; rootPath = FileSystems.newFileSystem(Paths.get(jarPath), classLoader).getPath("/"); } else { rootPath = Paths.get(url.toURI()); } // 递归扫描并匹配模式 Files.walk(rootPath) .filter(Files::isRegularFile) .filter(path -> path.getFileName().toString().matches(pattern.replace("*", ".*"))) .forEach(resources::add); } return resources; } }
注意:这种方法需要手动处理jar和目录的差异,且在Quarkus原生镜像模式下需要额外配置资源可访问性,推荐优先使用ClassPathUtils。
内容的提问来源于stack exchange,提问作者Michael Feichtegger
相关产品推荐
相关产品推荐

