hello,又到了通俗易懂的时候啦!欢迎小白看看,大佬勿喷。
@EnableWebMvc
当SpringBoot对SpringMVC的自动配置不需要时,选择自己所配置时,我们只需要在相关的配置类当中添加 @EnableWebMvc即可。
丢弃SpringMVC的自动配置可以有效的减少一些资源的加载以及消耗,大大提升项目运行效率。
下面主要针对源代码进行解答:
- 在配置类文件中加入@EnableWebMvc。
@EnableWebMvc
@Configuration
public class xxxMvcConfig extends WebMvcConfigurerAdapter{
...
}
- 点入EnableWebMvc类文件,查看其核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc{
...
}
- 因为其中导入DelegatingWebMvcConfiguration.class类文件,可以看到其中继承了WebMvcConfigurationSupport类文件
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport{
...
}
- 而在SpringMVC的自动配置类文件中,明显写到@CondtionalOnMissingBean(WebMvcConfigurationSupport.class),也就是当容器中没有WebMVCConfigurationSupport组件时,自动配置类才会判断为true,即自动配置类才会生效。
@Configuration
...
@CondtionalOnMissingBean(WebMvcConfigurationSupport.class)
...
public class WebMvcAutoConfiguration{
...
}
也就是当配置类使用@EnableWebMvc时,WebMVCConfigurationSupport组件则加载进容器中,因为容器中已经有该组件,所以SpringMVC的自动配置类文件则不会生效。