Spring Boot 为 Spring MVC 提供了适用于多数应用的自动配置功能( WebMvcAutoConfiguration )。
在Spring默认基础上,自动配置添加了以下特性:
引入 ContentNegotiatingViewResolver
和 BeanNameViewResolver beans
- 自动配置了视图解析器
ViewResolver
(根据方法返回值获取视图对象View,视图对象决定如何渲染?重
定向Or 转发) ContentNegotiatingViewResolver
: 组合所有的视图解析器的(通过源码可分析出)
public class ContentNegotiatingViewResolver {
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes , "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());
if (requestedMediaTypes != null) { //选择所有候选的视图对象
List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);
//从候选中选择最合适的视图对象
View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);
//存入所有视图解析器
private List<ViewResolver> viewResolvers; 107
protected void initServletContext(ServletContext servletContext) {
Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
//从容器中获取所有的视图解析器
this.obtainApplicationContext(), ViewResolver.class).values();
}
自定义视图解析器:可以@Bean
向容器中添加一个我们自定义的视图解析器,即可被容器管理使用
@Bean
public ViewResolver myViewResolver () {
return new MyViewResolver();
}
private class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null; }
}// DispatcherServlet.doDispatch 断点后,发送任意请求,可查看已被容器自动管理了
-
自动注册
Converter , GenericConverter , and Formatter beans。
-
Converter :转换器; 如: 文本类型转换目标类型, true 转 boolean类型
-
GenericConverter :转换器,Spring内部在注册时,会将Converter先转换为GenericConverter之后,
再统一对GenericConverter注册。 -
Formatter : 格式化器; 如: 2017/12/17 格式化 Date类型
@Bean
public FormattingConversionService mvcConversionService() {
//传入日期格式, spring.mvc.date-format配置日期格式
WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());
this.addFormatters(conversionService);
return conversionService;
}//将格式化器添加容器中
protected void addFormatters(FormatterRegistry registry) {
this.configurers.addFormatters(registry);
}
-
对
HttpMessageConverters
的支持。
SpringMVC 用它来转换Http请求和响应的;User _json User _xml
可以通过@Bean
向容器中添加一个我们自定义HttpMessageConverters
,即可被容器管理使用 -
自动注册
MessageCodesResolver
。
定义错误代码生成规则; -
自动注册
ConfigurableWebBindingInitializer 。
初始化所有 Web数据绑定器 对象, 比如 请求数据 ——》JavaBean -
对静态资源的支持,包括对 Webjars 的支持。
-
对静态首页 index.html 的支持。
-
对 自定义 Favicon 图标的支持