springboot与普通springmvc项目的不同在于springboot有自己的默认的springmvc配置,比如WebMvcAutoConfigurationAdapter等,下面看下相关部分核心代码:
WebMvcConfigurationSupport类的
代码语言:javascript复制 protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(stringConverter);
messageConverters.add(new ResourceHttpMessageConverter());
messageConverters.add(new SourceHttpMessageConverter<Source>());
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
messageConverters.add(new AtomFeedHttpMessageConverter());
messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
messageConverters.add(new MappingJackson2XmlHttpMessageConverter(
Jackson2ObjectMapperBuilder.xml().applicationContext(this.applicationContext).build()));
}
else if (jaxb2Present) {
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
messageConverters.add(new MappingJackson2HttpMessageConverter(
Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build()));
}
else if (gsonPresent) {
messageConverters.add(new GsonHttpMessageConverter());
}
}
springboot默认的mvc配置会调用WebMvcConfigurationSupport的addDefaultHttpMessageConverters方法,通过上面的代码我们可以看出springboot默认mvc配置会添加上面的默认HttpMessageConverter,所以我们在springboot项目中通过configureMessageConverters是无法直接覆盖掉所有的HttpMessageConverters,要想屏蔽springboot默认的mvc配置可以进行以下操作:
在这个configration类上面增加@EnableWebMvc注解,这样就会屏蔽掉springboot默认的mvc配置,但是不推荐,这样就会屏蔽掉其他的默认配置,比如ExceptionHandlerExceptionResolver等