Spring Boot应用程序中的资源访问

3
我有一个Spring boot web应用程序(嵌入式Jetty服务器)。所有的Java代码和资源都打包在JAR中并部署在服务器上。但是,有一个JSON文件在JAR外,但在类路径中。 即:

我的类路径是:/usr/local/myserver/
JSON文件位于:/usr/local/myserver/hello.json
JAR文件位于:/usr/local/myserver/app.jar

当我访问URL:https://IP:port/hello.json时,它会给出“404 文件未找到”错误。提到的IP是所有文件和JAR所在的服务器。我相信默认的资源路径是/static/..,其中包含在那个'static'目录中的任何文件都是可访问的。

我已经配置:

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/hello.json").addResourceLocations("file://localhost/usr/local/myserver/");
    }

我该如何访问JSON文件?
2个回答

0
你需要使用 "file://" 前缀 + 你的文件系统上的绝对路径 "/usr/local/myserver/"。
registry.addResourceHandler("/hello.json")
        .addResourceLocations("file:///usr/local/myserver/");

哇!我已经尝试了很多次了;我记得以前也曾尝试过上面的模式,但那时候没有成功。但现在不知怎么地它终于起作用了!!!谢谢。 - ndhar

0
如果“JSON”文件已经在类路径中,那么为什么不使用类路径前缀“classpath:”呢?
classpath:/usr/local/myserver/

如果您使用file:/前缀,则会使用URL类加载JSON文件,因此您需要提供绝对路径位置,例如:
如果是Windows系统:
file:/usr/local/myserver 

我的类路径是:**/usr/local/myserver/**,我尝试使用 **classpath:/**,但它不起作用。此外,在我上面编写的代码中,我使用了Linux服务器的绝对位置,即 **file://localhost/usr/local/myserver/**。 - ndhar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接