Springboot学习03-SpringMVC自动配置

前言

在SpringBoot官网对于SpringMVCde 自动配置介绍

1-原文介绍如下:

Spring MVC Auto-configuration

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

The auto-configuration adds the following features on top of Spring’s defaults:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars (covered later in this document)).
  • Automatic registration of ConverterGenericConverter, and Formatter beans.
  • Support for HttpMessageConverters (covered later in this document).
  • Automatic registration of MessageCodesResolver (covered later in this document).
  • Static index.html support.
  • Custom Favicon support (covered later in this document).
  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMappingRequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

2-谷歌翻译如下

Spring MVC自动配置

Spring Boot为Spring MVC提供自动配置,且适用于大多数应用程序。

自动配置在Spring默认配置基础上,添加了以下功能:

  • 包括:ContentNegotiatingViewResolver和BeanNameViewResolver bean。
  • 支持提供静态资源,包括对WebJars的支持。
  • 自动注册Converter,GenericConverter和Formatter bean。
  • 支持HttpMessageConverters。
  • 自动注册MessageCodesResolver(本文档后面会介绍)。
  • 静态 index.html 页面支持。
  • 自定义Favicon支持。
  • 自动使用ConfigurableWebBindingInitializer bean)。

如果要保留Spring Boot MVC功能并且想要添加其他MVC配置(interceptors,formatters,view controllers和其他功能),可以添加自己的@Configuration类,类型为WebMvcConfigurer,但不包含@EnableWebMvc。如果您希望可以自定义RequestMappingHandlerMapping,RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver实例,则可以声明WebMvcRegistrationsAdapter实例以提供此类组件。

如果您想完全控制Spring MVC,可以使用@EnableWebMvc添加自己的@Configuration注释。

以下正文,对上面标红的内容进行分析

正文

1- ContentNegotiatingViewResolver and BeanNameViewResolver beans

1-1-源码出处

public class WebMvcAutoConfiguration {
//-在Springboot启动初始化时,自动装载WebMvcAutoConfiguration类,
//其中包括WebMvcAutoConfiguration内部类WebMvcAutoConfigurationAdapter下的ContentNegotiatingViewResolver viewResolver()方法
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ResourceLoaderAware { @Bean
@ConditionalOnBean({ViewResolver.class})
@ConditionalOnMissingBean(
name = {"viewResolver"},
value = {ContentNegotiatingViewResolver.class}
)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));
resolver.setOrder(-2147483648);
return resolver;
} }
}
public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered, InitializingBean {
//2-ContentNegotiatingViewResolver 执行其内部initServletContext()初始化方法,从BeanFactoryUtils中获取全部ViewResolver
protected void initServletContext(ServletContext servletContext) {
Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.obtainApplicationContext(), ViewResolver.class).values();
ViewResolver viewResolver;
if (this.viewResolvers == null) { Iterator var3 = matchingBeans.iterator();
while(var3.hasNext()) {
viewResolver = (ViewResolver)var3.next();
if (this != viewResolver) {
this.viewResolvers.add(viewResolver);
}
}
}
…………………………省略
} //2-当一个请求进来时,调用ContentNegotiatingViewResolver 下的View resolveViewName()方法,,并返回bestView,主要包括beanName参数,即对应渲染的(比如:html)文件名称
@Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception {
//ContentNegotiatingViewResolver 根据文件名和请求头类型来决定返回什么样的View。而mediaTypes这个属性存储了 你请求后缀名 或者 参数 所对应 的mediaType
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
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);
if (bestView != null) {
//返回视图对象
return bestView;
}
}
……………省略
} //2-1-获取候选视图对象
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes) throws Exception {
List<View> candidateViews = new ArrayList();
if (this.viewResolvers != null) {
//获取全部视图解析器
Iterator var5 = this.viewResolvers.iterator();
//筛选出候选View
while(var5.hasNext()) {
…………………………省略
while(var11.hasNext()) {
String extension = (String)var11.next();
String viewNameWithExtension = viewName + '.' + extension;
view = viewResolver.resolveViewName(viewNameWithExtension, locale);
if (view != null) {
candidateViews.add(view);//获取view
}
}
} }
return candidateViews;
}
}

1-2-源码解释

  • 1-在Springboot启动初始化时,自动装载WebMvcAutoConfiguration类,其中包括WebMvcAutoConfiguration内部类WebMvcAutoConfigurationAdapter下的ContentNegotiatingViewResolver viewResolver()方法
  • 2-ContentNegotiatingViewResolver 执行其内部initServletContext()初始化方法,从BeanFactoryUtils中获取全部ViewResolver
  • 3-当一个请求进来时,调用ContentNegotiatingViewResolver 下的View resolveViewName()方法根据方法的返回值得到视图对象(View),,并返回bestView,主要包括beanName参数,即对应渲染的(比如:html)文件名称

1-3-自定义视图解析器

1-3-1-自定义解析其源码

@SpringBootApplication
public class SpringbootdemoApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
} //在Springboot启动时,加载自定义的MyViewResolver类
@Bean
public ViewResolver myViewResolver(){
return new MyViewResolver();
} //(这里为了方便,在启动类下写了一个内部类)
//MyViewResolver实现接口类ViewResolver
private static class MyViewResolver implements ViewResolver{ @Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
} }

1-3-2-源码解析

  • 1-自定义MyViewResolver 类必须实现ViewResolver接口
  • 2-并在Springboot初始化是,被自动加载

1-3-3-使用结果:在Spring分发请求时,发现自定义的MyViewResolver被被加载

2-支持提供静态资源,包括对WebJars的支持。请参考本人博客:https://www.cnblogs.com/wobuchifanqie/p/10112302.html

3-自动注册Converter,GenericConverter和Formatter bean

3-1-自定义Converter

//1-controller层
@Controller
public class DemoController {
Logger log = LoggerFactory.getLogger(DemoController.class); @RequestMapping(value="get/student")
public String getStudent(Student student,Model model){
log.debug("student: " + student);
model.addAttribute("student",student);
return "student";
} }
//2-自定义converter
@Configuration
public class StringToStudentConverrter implements Converter<String,Student> {
@Override
public Student convert(String s) {
//student=tyj-18
String[] split = s.split("-");
Student student = new Student(split[0],Integer.parseInt(split[1]));
return student;
}
}
//3-html示例
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${student.name}"></div>
<div th:text="${student.age}"></div>
<strong>success!</strong>
</body>
</html>

4-支持HttpMessageConverters:SpringMVC用来转换Http请求和响应的;是从容器中确定;获取所有的HttpMessageConverter

4-2-自定义HttpMessageConverters

//1-自定义HttpMessageConverters
public class MyMessageConveter extends AbstractHttpMessageConverter<Student>{ public MyMessageConveter() {
//Content-Type= application/xxx-tyj
super(new MediaType("application", "xxx-tyj", Charset.forName("UTF-8")));
} @Override
protected boolean supports(Class<?> aClass) {
// 表明只处理UserEntity类型的参数。
return Student.class.isAssignableFrom(aClass);
} //重写readlntenal 方法,处理请求的数据。代码表明我们处理由“-”隔开的数据,并转成 Student类型的对象。
@Override
protected Student readInternal(Class<? extends Student> aClass, HttpInputMessage httpInputMessage)
throws IOException, HttpMessageNotReadableException {
String content = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
String[] split = content.split("-");
return new Student(split[0],Integer.parseInt(split[1]));
} //重写writeInternal ,处理如何输出数据到response。
@Override
protected void writeInternal(Student student, HttpOutputMessage httpOutputMessage)
throws IOException, HttpMessageNotWritableException {
String out = "hello: " +student.getName() + " ,你今年" + student.getAge() + "了么?";
httpOutputMessage.getBody().write(out.getBytes());
}
}
//2-加载自定义的MyMessageConveter
@Configuration
public class MySpringBootConfig {
@Bean
public MyMessageConveter MyMessageConveter (){
return new MyMessageConveter();
}
}
//3-controller
@Controller
public class DemoController { @RequestMapping(value="hello/student",method = POST)
@ResponseBody
public Student helloStudent(@RequestBody Student student){
return student;
} }
接口测试
URL:POST localhost:8080/hello/student
header: Content-Type = application/xxx-tyj
body: tyj-21 返回值:hello: tyj ,你今年21了么?

4-3-添加一个converter的方式有三种

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
// 添加converter的第一种方式,代码很简单,也是推荐的方式
// 这样做springboot会把我们自定义的converter放在顺序上的最高优先级(List的头部)
// 即有多个converter都满足Accpet/ContentType/MediaType的规则时,优先使用我们这个
@Bean
public MyMessageConveter MyMessageConveter (){
return new MyMessageConveter();
}
// 添加converter的第二种方式
// 通常在只有一个自定义WebMvcConfigurerAdapter时,会把这个方法里面添加的converter(s)依次放在最高优先级(List的头部)
// 虽然第一种方式的代码先执行,但是bean的添加比这种方式晚,所以方式二的优先级 大于 方式一
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// add方法可以指定顺序,有多个自定义的WebMvcConfigurerAdapter时,可以改变相互之间的顺序
// 但是都在springmvc内置的converter前面
converters.add(new MyMessageConveter());
} // 添加converter的第三种方式
// 同一个WebMvcConfigurerAdapter中的configureMessageConverters方法先于extendMessageConverters方法执行
// 可以理解为是三种方式中最后执行的一种,不过这里可以通过add指定顺序来调整优先级,也可以使用remove/clear来删除converter,功能强大
// 使用converters.add(xxx)会放在最低优先级(List的尾部)
// 使用converters.add(0,xxx)会放在最高优先级(List的头部)
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyMessageConveter());
}
}

5-自动注册MessageCodesResolver:定义错误代码生成规则

6-静态 index.html 页面支持。请参考本人博客:https://www.cnblogs.com/wobuchifanqie/p/10112302.html

7-自定义Favicon支持。请参考本人博客:https://www.cnblogs.com/wobuchifanqie/p/10112302.html

8-自动使用ConfigurableWebBindingInitializer bean。

参考资料

1-https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration

2-http://www.cnblogs.com/huhx/p/baseusespringbootconverter1.html

3-https://www.cnblogs.com/page12/p/8166935.html

4-http://www.cnblogs.com/hhhshct/p/9676604.html

Springboot学习03-SpringMVC自动配置的更多相关文章

  1. Springboot学习:SpringMVC自动配置

    Spring MVC auto-configuration Spring Boot 自动配置好了SpringMVC 以下是SpringBoot对SpringMVC的默认配置:==(WebMvcAuto ...

  2. SpringBoot源码学习系列之SpringMVC自动配置

    目录 1.ContentNegotiatingViewResolver 2.静态资源 3.自动注册 Converter, GenericConverter, and Formatter beans. ...

  3. 【SpringBoot】SpringBoot与SpringMVC自动配置(五)

    本文介绍SpringBoot对Spring MVC自动配置,SpringBoot自动配置原理可以参考:[SpringBoot]SpringBoot配置与单元测试(二) 首先新建一个SpringBoot ...

  4. SpringBoot:配置文件及自动配置原理

    西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处!防君子不防小人,共勉! SpringBoot ...

  5. SpringBoot是如何实现自动配置的?--SpringBoot源码(四)

    注:该源码分析对应SpringBoot版本为2.1.0.RELEASE 1 前言 本篇接 助力SpringBoot自动配置的条件注解ConditionalOnXXX分析--SpringBoot源码(三 ...

  6. 这一次搞懂SpringBoot核心原理(自动配置、事件驱动、Condition)

    @ 目录 前言 正文 启动原理 事件驱动 自动配置原理 Condition注解原理 总结 前言 SpringBoot是Spring的包装,通过自动配置使得SpringBoot可以做到开箱即用,上手成本 ...

  7. SpringBoot Beans管理和自动配置

    原 SpringBoot Beans管理和自动配置 火推 02 2017年12月20日 21:37:01 阅读数:220 SpringBoot Beans管理和自动配置 @SpringBootAppl ...

  8. SpringBoot自定义starter及自动配置

    SpringBoot的核心就是自动配置,而支持自动配置的是一个个starter项目.除了官方已有的starter,用户自己也可以根据规则自定义自己的starter项目. 自定义starter条件 自动 ...

  9. SpringBoot扩展SpringMVC自动配置

    SpringBoot中自动配置了 ViewResolver(视图解析器) ContentNegotiatingViewResolver(组合所有的视图解析器) 自动配置了静态资源文件夹.静态首页.fa ...

  10. SpringBoot日记——SpringMvc自动配置与扩展篇

    为了让SpringBoot保持对SpringMVC的全面支持和扩展,而且还要维持SpringBoot不写xml配置的优势,我们需要添加一些简单的配置类即可实现: 通常我们使用的最多的注解是: @Bea ...

随机推荐

  1. 反射机制(java)

    反射机制 反射机制可通过在运行时加载类名而获取类,并对其进行操作.工厂模式,动态代理中较常用到. 在实际场景中:由于有好多类具有共同的接口样式,而他们又用的不是很频繁,如果在服务器中保有这些类会占用资 ...

  2. C++11并发之std::thread<转>

    最近技术上没什么大的收获,也是悲催的路过~ 搞一点新东西压压惊吧! C++11并发之std::thread 知识链接: C++11 并发之std::mutex C++11 并发之std::atomic ...

  3. 爬虫--requests模块高级(代理和cookie操作)

    代理和cookie操作 一.基于requests模块的cookie操作 引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests ...

  4. 推荐一款idea 翻译插件 ECTranslation

    无意中看到一款idea翻译插件, ECTranslation,才知道有这么个东西,推荐给看到的人吧,使用简单,值得拥有. 参考:http://p.codekk.com/detail/Android/S ...

  5. datasnap服务器支持的参数类型

    可作为参数的类型TDBXWideStringValueTDBXAnsiStringValueTDBXInt16ValueTDBXInt32ValueTDBXInt64ValueTDBXSingleVa ...

  6. ping ip多进程处理小程序

    最近,环境维护需要经常需要判断某些服务器上的IP是否可达,由于服务器数量较多,逐一手工ping检查太过繁琐.写个小程序使用. 实现和说明 1.使用配置文件ip.txt实现可配置指定ip列表. 2.利用 ...

  7. oracle归档日志关闭和打开

    查询归档日志状态 方法一 SQL> archive log list; 方法二 SQL> select name,log_mode from V$database; 打开归档日志 orac ...

  8. [ JAVA编程 ] double类型计算精度丢失问题及解决方法

    前言 如果你在测试金融相关产品,请务必覆盖交易金额为小数的场景.特别是使用Java语言的初级开发. Java基本实例 先来看Java中double类型数值加.减.乘.除计算式实例: public cl ...

  9. Ubuntu网卡配置

    目录 1.查看所有可用网卡 2.编辑配置文件 3.添加可用网卡信息 4.重启网络服务 5.查看网卡信息 1.查看所有可用网卡 $ ifconfig -a # -a display all interf ...

  10. [CI]CodeIgniter应用配置明细

    ---------------------------------------------------------------------------------------------------- ...