从文件系统提供静态资源| Spring Boot Web

Kum*_*hav 18 spring-mvc spring-boot

使用Spring Boot Web应用程序我尝试从项目外部的文件系统文件夹中提供静态资源.

文件夹结构如下: -

          src
             main
                 java
                 resources
             test
                 java
                 resources
          pom.xml
          ext-resources   (I want to keep my static resources here)
                 test.js
Run Code Online (Sandbox Code Playgroud)

弹簧配置: -

@SpringBootApplication
public class DemoStaticresourceApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(DemoStaticresourceApplication.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("file:///./ext-resources/")
                .setCachePeriod(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的浏览器中点击' http:// localhost:9999/test/test.js '会返回404.

我应该如何配置ResourceHandlerRegistry来提供上述'ext-resources'文件夹中的静态资源?

我应该能够为dev/prod环境打开/关闭缓存.

谢谢

更新1

给绝对文件路径有效: -

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**")
                .addResourceLocations(
                        "file:///C:/Sambhav/Installations/workspace/demo-staticresource/ext-resources/")
                .setCachePeriod(0);
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能提供相对位置?绝对路径将使我的生活在构建和部署过程中变得艰难.

And*_*son 27

file:///是指向文件系统根目录的绝对URL,因此,file:///./ext-resources/意味着Spring Boot正在查找ext-resources根目录中指定的目录中的资源.

更新您的配置以使用类似file:ext-resources/URL的内容.

  • 仅供参考...`WebMvcConfigurerAdapter` 已在 spring 5.0 中弃用。他们推荐使用`WebMvcConfigurer` 来配置你的 mvc。 (3认同)