代码之家  ›  专栏  ›  技术社区  ›  DerM

Spring引导服务静态内容:addResourceLocations与静态位置

  •  1
  • DerM  · 技术社区  · 7 年前

    我有一个标准的SpringBoot应用程序,尝试提供一些静态内容。我想将位置更改为文件系统上的特定文件夹。这些似乎是最常见的方法:

    在application.yaml中设置路径

    spring:
      resources:
        static-locations: "file:/here/some/path"
    

    使用 WebMvcConfigurer

    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
                .addResourceHandler("/**")
                .addResourceLocations("file:/here/some/path");
        }
    }
    

    这是我的问题:第一种方法有效,第二种方法无效,我无法找出原因。有什么提示吗?

    设置“静态位置”和“AddResourceLocations”之间有区别吗?调试的起点是什么?

    我想使用第二个,因为我想根据特定的条件设置路径。 谢谢!

    3 回复  |  直到 7 年前
        1
  •  0
  •   this_is_om_vm    7 年前

    附加此注释

    @启用WebMVC

    在你的 MVC配置 类。只要尝试它就可以解决您的问题。

        2
  •  0
  •   Sergey Ushakov    7 年前

    尝试将尾随斜杠添加到“file:/here/some/path”

    当您使用“spring.resources.static locations”时,它会自动在org.springframework.boot.autoconfigure.web.resourceproperties appendslashwificenecessary为您完成。

        3
  •  0
  •   DerM    7 年前

    我注意到它实际上是与

    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
                .addResourceHandler("/**")
                .addResourceLocations("file:/here/some/path");
        }
    }
    

    但是 出于某种原因,重定向到index.html被禁用(这是非常意外的行为)。所以我需要手动添加它。

    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
                .addResourceHandler("/**")
                .addResourceLocations("file:/here/some/path");
        }
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("forward:/index.html");
        }
    }