SpringBoot学习之路踩坑系列:访问静态资源
Posted 天天向上2015
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot学习之路踩坑系列:访问静态资源相关的知识,希望对你有一定的参考价值。
众所周知,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学习之路踩坑系列:访问静态资源的主要内容,如果未能解决你的问题,请参考以下文章
第259天学习打开(知识点回顾 springboot静态资源访问)
springboot学习入门简易版四---springboot2.0静态资源访问及整合freemarker视图层