苏州网站建设代理渠道,wordpress博客名字,wordpress 审核用户,搜索引擎app网上有很多文章说从spring boot2.0之后在构造spring配置文件时建议推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport #xff0c;经测试实现WebMvcConfigurer是没问题#xff0c;但继承WebMvcConfigurationSupport类是会导致自动配置失效的。
一、继承W…网上有很多文章说从spring boot2.0之后在构造spring配置文件时建议推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport 经测试实现WebMvcConfigurer是没问题但继承WebMvcConfigurationSupport类是会导致自动配置失效的。
一、继承WebMvcConfigurationSupport类是会导致自动配置失效的原因 在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后发现自动配置的静态资源路径classpath:/META/resources/classpath:/resources/classpath:/static/classpath:/public/不生效。 这是因为在 springboot的web自动配置类 WebMvcAutoConfiguration 上有条件注解
ConditionalOnMissingBean(WebMvcConfigurationSupport.class) 这个注解的意思是在项目类路径中 缺少 WebMvcConfigurationSupport类型的bean时改自动配置类才会生效所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。
如果想要使用自动配置生效又要按自己的需要重写某些方法比如增加 viewController 则可以自己的配置类可以继承 WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter 虽然还可以用但是看起来不好 。 这是类上的注释意思是spring 5.0后要使用Java8而在Java8中接口是可以有default方法的所以这个类就没必要了。所以我们只需要在自定义配置类中直接实现
二、继承WebMvcConfigurationSupport类如何配置拦截器的
Configuration
public class MyConfigurer extends WebMvcConfigurationSupport {Overrideprotected void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns(/**).excludePathPatterns(/emp/toLogin,/emp/login,/js/**,/css/**,/images/**);super.addInterceptors(registry);}Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler(/**).addResourceLocations(classpath:/static/);super.addResourceHandlers(registry);}
}注意这段代码
registry.addResourceHandler(/**).addResourceLocations(classpath:/static/);由于继承WebMvcConfigurationSupport后会导致自动配置失效所以这里要指定默认的静态资源的位置。同时要注意不能写成
registry.addResourceHandler(/static/**).addResourceLocations(classpath:/static/);