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<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;
        }
    }

查看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最基本的功能

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值