在SpringBoot环境中使用拦截器,继承自HandlerInterceptor
,进行注册时,实现WebMvcConfigurer
接口,重写 addInterceptors()
方法,添加@Component
注解添加到Spring容器来注册拦截器。
- 但是注意到
WebMvcConfigurer
上有个@EnableWebMvc
的提示,文档说明添加此注解可以实现自定义的Spring Mvc 配置。想起之前看视频讲到添加@EnableMWebmvc
注解可以全面托管Spring Mvc,会出现各种问题,于是搞清楚具体原因。 - 从Springboot 项目的启动类
@SpringBootApplication
开始,是一个聚合注解,包含了三个重要的注解@SpringBootConfiguration
、@EnableAutoConfiguration
和
@ComponentScan
。其中查看@EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
// AutoConfigurationImportSelector 继承自 ImportSelector,
// 载入selector,识别AutoConfigutaion类并import
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
...
}
- AutoConfiguration 类可通过 spring-boot-autoconfigure-2.0.6.RELEASE.jar/META-INF/spring.factories查看,列出了Springboot自动装配的类,找到
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
- 查看
WebMvcAutoConfiguration
,因此当Spring容器中出现WebMvcConfigurationSupport
bean 时,此自动配置失效
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
// 只有不在WebMvcConfigurationSupport 的bean 时才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
}
- 查看
@EnableWebmvc
,导入的DelegatingWebMvcConfiguration
继承自WebMvcConfigurationSupport
,所以开启此注解会导致springboot的mvc自动装配失效
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}