簡體   English   中英

在類路徑中啟動 spring 中的訪問文件夾

[英]access folder in spring boot in classpath

我正在嘗試訪問在 Spring 啟動應用程序的類路徑中創建的文件夾。 代碼片段如下:

ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
URL url = classLoader.getResource("converters");
LOGGER.debug("**************** url: " + url);
File file = new File(url.toURI());
        
Path path = Paths.get(file.getAbsolutePath());
Arrays.stream(path.toFile().listFiles()).forEach(f -> LOGGER.debug("*******files: " + f.getName()));
if (!path.toFile().isDirectory()) {
   throw new IllegalArgumentException(ErrorCode.INVALID_MAPPERS_DIRECTORY.formatMessage(path));
}

上面的代碼在 Intellij 中運行時沒有任何問題,我得到 url 如下:

文件:/C:/Users/user1/projects/my-service/test/build/resources/main/converters

當我在應用程序 rpm 內的 Linux 上運行它時,我得到以下 url 值:

jar:file:/opt/home/libexec/my-service-2.0.0-SNAPSHOT.jar./BOOT-INF/lib/my-service-api-2.0.0-SNAPSHOT.jar!/converters

為什么會有不同的行為?

區別在於包裝。 您的 IDE 不會 package 您的應用程序來運行它,它只是使用文件系統,因為這樣更快。 When you package your app and deploy all the resources that your ide can access from the file system are now packaged within your spring boot fat jar file. 在您的情況下,該文件位於my-service-api-2.0.0-SNAPSHOT.jar中,該文件封裝在您的胖 jar 中。

問題

我需要能夠引用用戶可能在我的 Spring 引導應用程序的類路徑中創建的文件夾。

解決方案

以下對我有用:

mapperFilesFolder = resolver.getResources("classpath*:" + mappersLocation + "/.");
Path path = Paths.get(mappersFolder[0].getURI());

暫無
暫無

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

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