1、前言:
SpringBoot的自动配置极大的方便了我们的开发,这种上手容易,但是在遇到问题的时候就不怎么容易解决了,一般的解决方案就是去一点点看源码,接下来对SpringBoot2.x引入静态资源类失效的问题进行分析。
1、问题重现
在springBoot2.x中如果想在配置类中设置访问某个页面,就会发现出现如下图找不到静态资源。
2、问题解析
因为在springBoot1.x中我们通过继承WebMvcConfigurerAdapter来实现页面跳转的配置,但是在springBoot2.x中我们发现WebMvcConfigureAdapter已经过时了,换成了WebMvcConfigurationSupport,此时我们换成了它,发现所有的静态资源都访问不了了,众所周知,静态资源类都是由SpirngBoot 自动配置的,那么我就可以从SpringBoot自动配置部分进行着手解决,且看源码中这段话:
ctrl+n 搜索 webMVCautoconfiguration 找到mvc的自动配置类,(或者从External Libraries–>spring-boot-autoconfigure–>autoconfigure–>servlet–>webMvcAutoConfiguration找到):
此时我们看到一个注解,@conditionalOnMissingBean,这个注解的意思就是如果用户自定义了WebMvcConfigurationSupport这个类,那么就MVC的自动配置就失效了,如果没有定义WebMvcConfigurationSupport,那么才会走MVC自动配置的,所以如下图,此时MVC的自动配置全部失效,
上图中展示了webjars中的静态资源的默认配置路径,接下来点击getStaticLocations() 进入到本地的默认的静态资源配置:
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
/**
* Whether to enable default resource handling.
*/
private boolean addMappings = true;
private final Chain chain = new Chain();
private final Cache cache = new Cache();
public String[] getStaticLocations() {
return this.staticLocations;
}
综上,所以此时我们用了WebMvcConfigurationSupport,那么MVC的自动配置就失效了,因此访问静态资源全都失效,(包括webjars),我们可以自己进行配置,如下:
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport{
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/atguigu").setViewName("success");
registry.addViewController("/").setViewName("index");
registry.addViewController("index.html").setViewName("index");
}
}
配置完上面之后,这次就可以访问resources下的静态资源了。