准备工作
Spring MVC Auto-configuration
// Spring Boot为Spring MVC提供了自动配置,它可以很好地与大多数应用程序一起工作。
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
// 自动配置在Spring默认设置的基础上添加了以下功能:
The auto-configuration adds the following features on top of Spring’s defaults:
// 包含视图解析器
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
// 支持静态资源文件夹的路径,以及webjars
Support for serving static resources, including support for WebJars
// 自动注册了Converter:
// 转换器,这就是我们网页提交数据到后台自动封装成为对象的东西,比如把"1"字符串自动转换为int类型
// Formatter:【格式化器,比如页面给我们了一个2019-8-10,它会给我们自动格式化为Date对象】
Automatic registration of Converter, GenericConverter, and Formatter beans.
// HttpMessageConverters
// SpringMVC用来转换Http请求和响应的的,比如我们要把一个User对象转换为JSON字符串,可以去看官网文档解释;
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).
// 初始化数据绑定器:帮我们把请求数据绑定到JavaBean中!
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
/*
如果您希望保留Spring Boot MVC功能,并且希望添加其他MVC配置(拦截器、格式化程序、视图控制器和其他功能),则可以添加自己
的@configuration类,类型为webmvcconfiguer,但不添加@EnableWebMvc。
如果希望提供
RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义
实例,则可以声明WebMvcRegistrations实例来提供此类组件。
*/
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 want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
// 如果您想完全控制Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc进行注释。
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
添加一个MVC的配置
-
首先编写一个MVC的配置类,并标注注解@Configuration
-
添加一个类型为webMvcConfigurer的类
全局搜索一下,发现该类是一个接口,因此我们要想添加MVC的配置必须实现这个接口
- 我们自定义一个视图解析器,先去搜索一个ViewResolver,它是一个接口,里面有一个方法resolveViewName(),我们可以看看它的实现类是怎么实现的
先观察其中一个实现类,ContentNegotiatingViewResolver内容协商视图解析器 ,/ContentNegotiatingViewResolver使用所有其他视图解析器来定位视图,因此它应该具有较高的优先级
进入这个类中的实现resolveViewName()方法看看,找到对应的解析视图的代码
// 注解说明:@Nullable 即参数可为null
@Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
if (requestedMediaTypes != null) {
// 获取候选的视图对象
List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
// 选择一个最适合的视图对象,然后把这个对象返回
View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
if (bestView != null) {
return bestView;
}
}
进行查看getCandidateViews(),看看它是如何获取候选的视图,它是把所有的视图解析器进行循环遍历,挨个解析,进行添加候选视图
总结:ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的
再来看看它的组合逻辑,看到有个属性viewResolver,看看它是在哪里进行赋值的
protected void initServletContext(ServletContext servletContext) {
// 这里它是从beanFactory工具中获取容器中的所有视图解析器
// ViewRescolver.class 把所有的视图解析器来组合的
Collection<ViewResolver> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();
if (this.viewResolvers == null) {
this.viewResolvers = new ArrayList<>(matchingBeans.size());
for (ViewResolver viewResolver : matchingBeans) {
if (this != viewResolver) {
this.viewResolvers.add(viewResolver);
}
}
}
既然它是在容器中去找视图解析器,我们是否可以猜想,我们就可以去实现一个自己的视图解析器
- 在我们的配置类中写一个视图解析器类
//拓展(添加)springMvc配置
//添加@Configuration注解代表是一个spring的组件(配置类)
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//该注解是将方法的返回值对象存入springIOC容器中
@Bean
public ViewResolver getMyViewResolver(){
return new MyViewResolver();
}
//静态内部类,视图解析器就需要实现ViewResolver接口
private static class MyViewResolver implements ViewResolver{
//重新一个resolveViewName方法
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
- 我们来测试一下我们的视图解析器有没有起作用,由于MVC核心是前端控制器DispatcherServlet 进行请求分发,我们查找一下它的doDispatch方法,加一个断点进行调试一下,因为所有的请求都会经过这个方法进行分发
- 启动springboot程序,访问任意一个页面,看看debug信息,发现我们自己定义的视图解析器确实已经起作用了,被添加进去作为视图解析器
我们再添加一个webMVC的配置,添加一个视图跳转
//拓展(添加)springMvc配置
//添加@Configuration注解代表是一个spring的组件(配置类)
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//添加一个视图控制
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//添加一个视图跳转,设置请求路径,响应对应的视图名字
registry.addViewController("/a").setViewName("test");
}
}
测试:
格式化转化器
- 我们可以进去WebMvcAutoConfiguration类中搜索,发现有一个方法FormattingConversionService(),有一个mvcProperties的MVC配置类中有getFormat()方法
@Bean
@Override
public FormattingConversionService mvcConversionService() {
Format format = this.mvcProperties.getFormat();
WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()
.dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
addFormatters(conversionService);
return conversionService;
}
分析一下springMVC的原理
-
WebMvcAutoConfiguration 是 SpringMVC的自动配置类,里面有一个类WebMvcAutoConfigurationAdapter
-
这个类上有一个注解,在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class),进入EnableWebMvcConfiguration这个类继承了一个父类DelegatingWebMvcConfiguration
- DelegatingWebMvcConfiguration 类中有一个方法setConfigurers()
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
// 从容器中获取所有的webmvcConfigurer
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
}
- 在这个类中去寻找一个我们刚才设置的viewController当做参考,发现它调用了一个configurers.addViewControllers()方法
- 进入configurers.addViewControllers()方法查看
public void addViewControllers(ViewControllerRegistry registry) {
// 将所有的WebMvcConfigurer相关配置来一起调用!包括我们自己配置的和Spring给我们配置的
for (WebMvcConfigurer delegate : this.delegates) {
delegate.addViewControllers(registry);
}
}
总结:所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用
全面接管SpringMVC
官方文档:If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc
全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置,即springMVC的自动配置失效,只需要我们的配置类中加@EnableWebMvc注解即可
如果我们全面接管了SpringMVC了,我们之前SpringBoot给我们配置的静态资源映射一定会无效
- 在我们自定义的WebMVC配置类中加入@EnableWebMvc注解
//拓展(添加)springMvc配置
//添加@Configuration注解代表是一个spring的组件(配置类)
@Configuration
@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
}
访问静态资源路径:
- 将自定义 WebMVC配置类中的@EnableWebMvc注解注销
再次访问静态资源路径:
发现所有的SpringMVC自动配置都失效了
思考为什么加入一个注解,自动配置就失效了?
- 从@EnableWebMvc中点进去查看源码
发现它导入了一个类DelegatingWebMvcConfiguration
- 发现它继承了一个父类WebMvcConfigurationSupport
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
- 我们再看一下webMvc的自动配置类WebMvcAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
// 这个注解的意思就是:容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
总结:@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了,导致webMvc的自动配置类失效