之前做了一个demo,当时并没有注意,后来发现静态资源不能访问了。
Spring Boot自动配置了classpath:/static/下面的资源为静态资源,后来网上找了很多的方法都试过了,解决不了。
于是我重新写了一个项目,把这个旧项目的配置一个一个的移动过去,最后发现是我配置的拦截器的问题。因为我配置拦截器继承的类是:WebMvcConfigurationSupport这个类,它会让spring boot的自动配置失效。
怎么解决呢?
第一种可以继承WebMvcConfigurerAdapter,当然如果是1.8+WebMvcConfigurerAdapter这个类以及过时了,可以直接实现WebMvcConfigurer接口,然后重写addInterceptors来添加拦截器:
1
2
3
4
5
6
7
8
9
10
|
@Configuration
public
class
InterceptorConfig
implements
WebMvcConfigurer {
@Override
public
void
addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(
new
UserInterceptor()).addPathPatterns(
"/user/**"
);
WebMvcConfigurer.
super
.addInterceptors(registry);
}
}
|
或者还是继承WebMvcConfigurationSupport,然后重写addResourceHandlers方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Configuration
public
class
InterceptorConfig
extends
WebMvcConfigurationSupport {
@Override
protected
void
addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(
new
UserInterceptor()).addPathPatterns(
"/user/**"
);
super
.addInterceptors(registry);
}
@Override
protected
void
addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/**"
).addResourceLocations(
"classpath:/static/"
);
super
.addResourceHandlers(registry);
}
}
|
转自:https://www.acgist.com/article/488.html