Spring MVC配置 EnableWebMvc,WebMvcConfigurationSupport,WebMvcAutoConfiguration
@EnableWebMvc
声明
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
//注意这里
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
DelegatingWebMvcConfiguration
是WebMvcConfigurationSupport
的子类
注释
根据注释可以看到EnableWebMvc
的作用有2个
- 导入
WebMvcConfigurationSupport
的配置
@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = MyConfiguration.class)
public class MyConfiguration {
}
- 自定义配置,需要实现
WebMvcConfigure
接口
@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = MyConfiguration.class)
public class MyConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
formatterRegistry.addConverter(new MyConverter());
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyHttpMessageConverter());
}
}
注意: 只有一个@Configuration类可以具有@EnableWebMvc批注,以导入Spring Web MVC配置。但是,可以有多个实现WebMvcConfigurer的@Configuration类,以自定义提供的配置。
如果WebMvcConfigurer没有公开一些需要配置的高级设置,请考虑删除@EnableWebMvc批注并直接从WebMvcConfigurationSupport或DelegatingWebMvcConfiguration进行扩展
SpringBoot 中
WebMvcAutoConfiguration
@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
则自动配置失效
即: 使用@EnableWebMvc
时WebMvcAutoConfiguration
失效