首页 > 编程语言 > 详细

SpringBoot学习之路踩坑系列:访问静态资源

时间:2018-08-15 10:08:09      阅读:122      评论:0      收藏:0      [点我收藏+]

众所周知,SpringBoot的静态资源默认路径定义在

org.springframework.boot.autoconfigure.web.ResourceProperties

 

1 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
2             "classpath:/META-INF/resources/", "classpath:/resources/",
3             "classpath:/static/", "classpath:/public/" };


不能访问静态资源的原因:

1. 使用@EnableWebMvc:

启用Spring MVC pattern,这时SpringBoot的默认配置就不生效了,静态资源需要放在webapp目录下

 

2. 配置拦截器

2.1 继承WebMvcConfigurationSupport

在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。

 

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
    WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
    ValidationAutoConfiguration.class })

这个注解的意思是在项目类路径中 缺少 WebMvcConfigurationSupport类型的bean时改自动配置类才会生效,所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。

如果想要使用自动配置生效,又要按自己的需要重写某些方法,比如增加 viewController ,则可以自己的配置类可以继承  WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还可以用,但是看起来不好 = =。

 

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
            .addResourceLocations("classpath:/META-INF/resources/")
            .addResourceLocations("classpath:/resources/")
            .addResourceLocations("classpath:/static/")
            .addResourceLocations("classpath:/public/");
    super.addResourceHandlers(registry);
}

 

SpringBoot学习之路踩坑系列:访问静态资源

原文:https://www.cnblogs.com/frank2015/p/9479609.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!