Spring Boot静态资源不能访问问题

0

之前做了一个demo,当时并没有注意,后来发现静态资源不能访问了。

Spring Boot自动配置了classpath:/static/下面的资源为静态资源,后来网上找了很多的方法都试过了,解决不了。

于是我重新写了一个项目,把这个旧项目的配置一个一个的移动过去,最后发现是我配置的拦截器的问题。因为我配置拦截器继承的类是:WebMvcConfigurationSupport这个类,它会让Spring Boot的自动配置失效。

👿

怎么解决呢?

  • 继承WebMvcConfigurerAdapter,当然如果使用Java8+,那么WebMvcConfigurerAdapter这个类以及过时了,可以直接实现WebMvcConfigurer接口,然后重写addInterceptors来添加拦截器:
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new UserInterceptor()).addPathPatterns("/user/**");
		WebMvcConfigurer.super.addInterceptors(registry);
	}

}
  • 继承WebMvcConfigurationSupport,然后重写addResourceHandlers方法:
@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);
	}
	
}

除此之外,还有一个注解@EnableWebMvc,也会让自动配置失效,就这样。
😎