【问题标题】:Add external resources folder to Spring Boot将外部资源文件夹添加到 Spring Boot
【发布时间】:2015-11-27 03:16:25
【问题描述】:

我想添加一个相对于 jar 位置的资源文件夹(除了我的 jar 中打包的资源),例如:

/Directory
    Application.jar
    /resources
        test.txt

我尝试了以下方法:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
            .addResourceLocations("/resources/", "file:/resources/");
}

我也试过了:

.addResourceLocations("/resources/", "file:resources/");

使用任一设置访问 http://localhost:8080/resources/test.txt 会导致出现白标错误页面。我该如何解决这个问题?

【问题讨论】:

    标签: java spring spring-mvc spring-boot


    【解决方案1】:

    您的第二种方法可行:

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/", "file:resources/");
    }
    

    如果您从 /Directory 启动 Spring Boot,因为 file:resources/ 是相对路径。

    cd Directory
    java -jar Application.jar
    

    如果你能把所有东西都打包到jar里就好了,但是如果你必须引用外部资源,你应该使用absolute paths来避免这样的问题。

    【讨论】:

      【解决方案2】:
       @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
          registry
                  .addResourceHandler("/files/**")
                  .addResourceLocations("file:/location1/", "file:/location2/");
      }
      

      使用http://localhost:{port}/files/image.png 访问文件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 2020-11-30
        • 2017-03-13
        • 2019-04-15
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        相关资源
        最近更新 更多