简体   繁体   English

在类路径中启动 spring 中的访问文件夹

[英]access folder in spring boot in classpath

I am trying to get access to a folder that is created in the classpath in a Spring boot application.我正在尝试访问在 Spring 启动应用程序的类路径中创建的文件夹。 A snippet of the code is below:代码片段如下:

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));
}

The code above runs without any issues when I run it in Intellij and I get the url as below:上面的代码在 Intellij 中运行时没有任何问题,我得到 url 如下:

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

When I run it on Linux inside the application rpm, I get the url value below:当我在应用程序 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 jar:file:/opt/home/libexec/my-service-2.0.0-SNAPSHOT.jar./BOOT-INF/lib/my-service-api-2.0.0-SNAPSHOT.jar!/converters

Any reason why is the different behavior?为什么会有不同的行为?

The difference is the packaging.区别在于包装。 Your IDE does not package your application to run it, it just uses the file system as this is faster.您的 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. 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. In your case the file is inside the my-service-api-2.0.0-SNAPSHOT.jar which is packaged inside your fat jar.在您的情况下,该文件位于my-service-api-2.0.0-SNAPSHOT.jar中,该文件封装在您的胖 jar 中。

Problem问题

I need to be able to have a reference to a folder that a user may create in the classpath of my Spring Boot application.我需要能够引用用户可能在我的 Spring 引导应用程序的类路径中创建的文件夹。

Solution解决方案

The following worked for me:以下对我有用:

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