當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring Boot-@EnableWebMvc注解
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot-@EnableWebMvc注解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
作用:當配置類中添加了該注解了之后,就表示某個模塊的自動配置就都失效了,全部都要自己配置
例如下面這個MVC模塊的配置類
/*** @author:抱著魚睡覺的喵喵* @date:2020/12/18* @description:*/ //使用WebMvcConfigurer接口擴展Spring MVC的功能 @Configuration @EnableWebMvc public class MyMVcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//向瀏覽器發送/hao請求來到successregistry.addViewController("/hao").setViewName("forward:success");} }自此這段代碼就表示SpringMVC的自動配置就都失效了
為了加一個@EableWebMvc注解,自動配置就都失效了呢?
原理如下:
ctrl+右鍵點擊該注解查看源碼
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Import({DelegatingWebMvcConfiguration.class}) public @interface EnableWebMvc { }其中的DelegatingWebMvcConfiguration是核心-》繼續進去查看源碼
核心的代碼如下
我們發現這個類繼承了WebMvcConfigurationSupport,那這和自動配置失效有什么聯系呢?
重點來了
查看WebMvcAutoConfiguration ---- web模塊自動配置類-》源碼
頭部代碼如下
@Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration {其中的@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)是關鍵,它的意思是容器中沒有WebMvcConfigurationSupport這個類時,自動配置類才會生效
所以我們就明白了,因為@EableConfiguration注解中的DelegatingWebMvcConfiguration繼承了WebMvcConfigurationSupport,所以才會導致自動配置類失效
===========================================================
總結:
@EnableWebMvc將WebMvcConfigurationSupport組件導入容器里了,WebMvcConfigurationSupport里只有基礎的功能
總結
以上是生活随笔為你收集整理的Spring Boot-@EnableWebMvc注解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实现WebMvcConfigurer接口
- 下一篇: 嵌入式Servlet容器