簡體   English   中英

如何從與 Quarkus 模式匹配的類路徑加載資源

[英]How to load resources from classpath matching a pattern with Quarkus

我正在嘗試從類路徑加載包含特定模式(例如 *.properties)的所有資源。 因此我嘗試使用

ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
ArrayList<URL> resources = Collections.list(classLoader.getResources("")); 
resources.add(classLoader.getResource("org"));

在下一步中,我遍歷了 URL 資源列表,創建了適當的java.nio.FileSystem並使用PathMatcher查找所需的資源。

由於以下原因,此解決方案不起作用:

  • 將找不到根目錄中的資源,因為classloader.getResource()不適用於""null/
  • prod 配置文件的行為當然與 dev 配置文件完全不同

Quarkus 有沒有辦法使用模式從類路徑加載資源列表。

提前致謝並致以最誠摯的問候

ClassLoader.getResources("name")枚舉所有具有名稱的資源。 但不枚舉名為“名稱”的目錄中的“文件”。

例如,您可能需要包含文件 /my.properties 的/my.properties 在這種情況下,方法ClassLoader.getResources("my.properties")為每個文件返回兩個 URL。

我通過以下方式解決了這個問題:

首先,我將此 maven 依賴項添加到我的項目中:

        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.10.2</version>
        </dependency>

該庫提供了一個名為ClasspathHelper的 class,已按照以下代碼片段中的說明使用。

Collection<URL> classpathURLs = ClasspathHelper.forPackage("org", (ClassLoader[]) null);

Path path = null;
FileSystem fileSystem = null;
        
for (URL classpathURL : classpathURLs) {
    try {
        if (classpathURL.toString().startsWith("jar:file:/")) {
            fileSystem = FileSystems.newFileSystem(classpathURL.toURI(), new HashMap<>());
            path = fileSystem.getPath("/");
        } else {
            fileSystem = FileSystems.getDefault();
            path = fileSystem.getPath(classpathURL.getPath());
        }
               
        PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:**/*.properties");
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(path)) {
                    String resourceName = (path.getClass().getName().contains("ZipPath") ? path.toString() : path.toFile().getName());
                    // resource found - do further processing
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (URISyntaxException | IOException ex) {
        // handle exceptions
    }
}

如您所見, classpathURL的列表將從classpathHelper返回。 這些 URL 以jar:file:/或以file:/ 對於每種情況,都會創建一個適當的FileSystemPath 最后,將使用java.nio.PathMatcherSimpleFileVisitor來查找所需的資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM