在spring-boot+spring mvc 的项目中,有我们需要自己配置一些项目的设置,就会涉及到三个类(@EnableWebMvc 、WebMvcConfigurationSupport和WebMvcConfigurationAdapter),那么,他们之间有什么关系呢?
首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法。
翻源代码:
@EnableWebMvc
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer
* @see org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
* @see org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
有以下几种使用方式:
@EnableWebMv + extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可(友情提示,最新版spring boot 因为jdk已经支持接口默认方法实现,所以WebMvcConfigurationAdapter已经过时),这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置
extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置
有时候我们我们需要自定义一些配置
比如:Spring Boot 定制HTTP消息转换器
总结
使用 @EnableWebMvc 注解会屏蔽springboot的@EnableAutoConfiguration,需要自己设置MessageConverter;
默认使用 @EnableAutoConfiguration 注解,读取 application.properties 或 application.yml 文件中的配置。
参考