spring boot中慎用@EnableWebMvc - 因使用拦截器开始

在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 {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值