在之前的时候我先是学习了一些spring boot的初级知识,为了能够更好地适应这种新的方式,我又去配置并简单学习了初级的spring MVC,当然spring boot对spring MVC的自动配置可以满足我们的大部分需求,但是我们也可以通过自定义配置类并实现WebMvcXonfigurer接口来定制spring MVC配置。
Spring Boot 为 Spring MVC 提供的 auto-configuration 适用于大多数应用,并在Spring 默认功能上添加了以下特性:
-
引入ContentNegotiatingViewResolver 和 BeanNameViewResolver beans。
-
对静态资源的支持,包括对WebJars 的支持。
-
自动注册Converter,GenericConverter,Formatter beans。
-
对HttpMessageConverters 的支持。
-
自动注册MessageCodeResolver。
-
对静态index.html的支持。
-
对自定义Favicon的支持。
-
自动使用 ConfigurableWebBindingInitializer bean。
如果保留Spring Boot MVC特性,只需添加其他的MVC配置(拦截器,格式化处理器,视图控制器等),可以添加自己的WebMvcConfigurerAdapter 类型的@Configuration类,而不需要注解@EnableWebMvc。如果希望使用自定义的RequestMappingHandlerMapping,RequestMappingHandlerAdapter,或ExceptionHandlerExceptionResolver,可以声明一个WebMvcRegistrationsAdapter实例提供这些组件。
Spring MVC 使用HttpMessageConverter 接口转换HTTP 请求和响应,合适的默认配置可以开箱即用,例如对象自动转换为JSON(使用Jackson库)或XML(如果Jackson XML扩展可用,否则使用JAXB),字符串默认使用UTF-8编码。
可以使用Spring Boot 的HttpMessageConverters 类添加或自定义转换类:
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;
@Configuration
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}
}