栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot MVC自动配置原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot MVC自动配置原理

源码分析 WebMvcAutoConfiguration 类

在WebMvcAutoConfiguration找到viewResolver()

ContentNegotiatingViewResolver()内容协商视图解析器,自动配置了viewResolver(),点击查看源码

@Nullable //说明参数可为空
public View resolveViewName(String viewName, Locale locale) throws Exception {
    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
    Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
    List requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());
    if (requestedMediaTypes != null) {
           //获取候选的视图解析器
        List candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);
           //选择最合适的视图解析器并返回
        View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);
        if (bestView != null) {
            return bestView;
        }
    }

查看getCandidateViews()源码可知道,它是用循环将视图器挨个解析


所以ContentNegotiatingViewResolver 是用来组合所有视图解析器的

继续分析

WebMvcAutoConfiguration 是 SpringMVC的自动配置类,里面有一个类WebMvcAutoConfigurationAdapter, 这个类上有一个注解,在做其他自动配置时会导入:@import(EnableWebMvcConfiguration.class),就会调用所有的WebMvcConfiguration,包括自定义的。


全面接管SpringMVC
全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置。
只需在我们的配置类中要加一个@EnableWebMvc,但是加上注解所有的自动配置都会失效.


导入了DelegatingWebMvcConfiguration类
进去查看源码,发现集成继承了WebMvcConfigurationSupport

再回来看MVC自动配置

@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组件导入进来了,而导入的等待WebMvcConfigurationSupport只是SpringMVC最基本的功能

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号