Springboot学习03-SpringMVC自动配置
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
andBeanNameViewResolver
beans. - Support for serving static resources, including support for WebJars (covered later in this document)).
- Automatic registration of
Converter
,GenericConverter
, andFormatter
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 RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
, 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。
参考资料
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自动配置的更多相关文章
- Springboot学习:SpringMVC自动配置
Spring MVC auto-configuration Spring Boot 自动配置好了SpringMVC 以下是SpringBoot对SpringMVC的默认配置:==(WebMvcAuto ...
- SpringBoot源码学习系列之SpringMVC自动配置
目录 1.ContentNegotiatingViewResolver 2.静态资源 3.自动注册 Converter, GenericConverter, and Formatter beans. ...
- 【SpringBoot】SpringBoot与SpringMVC自动配置(五)
本文介绍SpringBoot对Spring MVC自动配置,SpringBoot自动配置原理可以参考:[SpringBoot]SpringBoot配置与单元测试(二) 首先新建一个SpringBoot ...
- SpringBoot:配置文件及自动配置原理
西部开源-秦疆老师:基于SpringBoot 2.1.6 的博客教程 秦老师交流Q群号: 664386224 未授权禁止转载!编辑不易 , 转发请注明出处!防君子不防小人,共勉! SpringBoot ...
- SpringBoot是如何实现自动配置的?--SpringBoot源码(四)
注:该源码分析对应SpringBoot版本为2.1.0.RELEASE 1 前言 本篇接 助力SpringBoot自动配置的条件注解ConditionalOnXXX分析--SpringBoot源码(三 ...
- 这一次搞懂SpringBoot核心原理(自动配置、事件驱动、Condition)
@ 目录 前言 正文 启动原理 事件驱动 自动配置原理 Condition注解原理 总结 前言 SpringBoot是Spring的包装,通过自动配置使得SpringBoot可以做到开箱即用,上手成本 ...
- SpringBoot Beans管理和自动配置
原 SpringBoot Beans管理和自动配置 火推 02 2017年12月20日 21:37:01 阅读数:220 SpringBoot Beans管理和自动配置 @SpringBootAppl ...
- SpringBoot自定义starter及自动配置
SpringBoot的核心就是自动配置,而支持自动配置的是一个个starter项目.除了官方已有的starter,用户自己也可以根据规则自定义自己的starter项目. 自定义starter条件 自动 ...
- SpringBoot扩展SpringMVC自动配置
SpringBoot中自动配置了 ViewResolver(视图解析器) ContentNegotiatingViewResolver(组合所有的视图解析器) 自动配置了静态资源文件夹.静态首页.fa ...
- SpringBoot日记——SpringMvc自动配置与扩展篇
为了让SpringBoot保持对SpringMVC的全面支持和扩展,而且还要维持SpringBoot不写xml配置的优势,我们需要添加一些简单的配置类即可实现: 通常我们使用的最多的注解是: @Bea ...
随机推荐
- AJAX之发送GET请求
用jquery发送get请求 function AjaxSubmit1() { $.ajax({ //用jQuery发送 url: '/app04/ajax1/', type: 'GET', data ...
- C# 简单的定时关机
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- match()方法解析
match()方法支持正则表达式的String对象的方法. 上篇我说了search()方法,也支持正则表达式的String对象,那么match()方法跟search()方法有什么不同呢?我们来看看. ...
- java Overloaded的方法是否可以改变返回值的类型?
刚才看到这样一个题,下面的解释很乱,所以还是做一下试验比较好 public class Test { public static void main(String[] args){ Bae b = n ...
- css3的2D和3D的转换
一:2D转换: 通过 CSS3 transform转换,我们能够对元素进行移动.缩放.转动.拉长或拉伸. 2D移动:translate().使用translate()函数,你可以把元素从原来的位置移 ...
- Python自动化运维开发实战 三、python文件类型
导语: python常用的有3种文件类型 1. 源代码 py 2. 字节代码 pyc 3. 优化代码 pyo 源代码: python源代码的文件以”py"为扩展名,由python程序解释,不 ...
- python基础学习Day15 面向对象、类名称空间、对象名称空间 (2)
一.类 先看一段代码: class Person: animal = '高级动物' walk_way = '直立行走' # 静态属性,静态变量,静态字段 language = '语言' def __i ...
- js高级-函数的四种调用模式
1.对象方法调用模式 方法内部的this指向当前调用者的对象d 定义类 (构造函数) function Dog (dogName){ //创建一个空对象 让空对象==this this.name ...
- SPSS-聚类分析
聚类分析(层次聚类分析(Q型聚类和R型聚类).快速聚类分析) 聚类分析的实质:是建立一种分类方法,它能够将一批样本数据按照他们在性质上的亲密程度在没有先验知识的情况下自动进行分类.这里所说的类就是一个 ...
- windows 下 redis安装
在D盘新建文件夹[redis],右键解压Redis ZIP包,把所有文件解压到redis文件夹中.(其他盘符也可以滴^_^) 文件介绍: redis-benchmark.exe #基准 ...