简体   繁体   English

在Spring Boot中无法解析类路径资源

[英]Classpath resource not resolving in spring boot

I am using spring boot and I have a file in resources folder. 我正在使用Spring Boot,并且资源文件夹中有一个文件。 I am using digital ocean machine and when i run the application using java -jar mywebapp.war, I am unable to access the file from classpath. 我正在使用数字海洋机,并且当我使用java -jar mywebapp.war运行应用程序时,无法从类路径访问文件。 I am accessing it using following standard syntax: 我正在使用以下标准语法进行访问:

File file = new ClassPathResource("mfile").getFile();

I am getting error that class path resource cannot be resolved to absolute path. 我收到错误消息,指出类路径资源无法解析为绝对路径。 The problem I see is that it is showing the path with ! 我看到的问题是它正在显示路径! marks as follows: 标记如下:

/home/u/webapp/target/mywebapp.war!/WEB-INF/classess!/mfile

What am I doing wrong here? 我在这里做错了什么?

Since you're running it with java -jar you should build it as a JAR file instead of WAR. 由于使用java -jar运行它,因此应将其构建为JAR文件而不是WAR。

Read more: https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html 了解更多: https//docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html

Get file does not work while running as jar.you should get it as a resource Stream. 作为jar运行时,获取文件不起作用。您应将其作为资源流获取。

ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("/file.xsd") ;
        File file = File.createTempFile("file", ".xsd");
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } finally {
            IOUtils.closeQuietly(inputStream);

it gets you a file. 它会为您提供文件。 if the requirement is to get as a file. 如果要求是作为文件获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM