SpringMVC源码解析(一):web容器启动流程

SpringMVC源码系列文章

SpringMVC源码解析(一):web容器启动流程


目录

  • 一、SpringMVC全注解配置
    • 1、pom文件
    • 2、web容器初始化类(代替web.xml)
    • 3、SpringMVC配置类(代替springmvc.xml)
    • 4、测试Controller
  • 二、SpringServletContainerInitializer
    • 1、web容器初始化入口
    • 2、SpringServletContainerInitializer的作用解析
  • 三、自定义配置类的加载
    • 1、AbstractDispatcherServletInitializer注册前端控制器
      • 1.1、创建web注解容器
      • 1.2、创建DispatcherServlet对象
      • 1.3、注册过滤器
    • 2、DispatcherServlet初始化
  • 四、@EnableWebMvc解析
    • 1、WebMvcConfigurer接口
    • 2、DelegatingWebMvcConfiguration
    • 3、WebMvcConfigurationSupport
      • 3.1、处理器映射器和处理器适配器
      • 3.2、RequestMappingHandlerMapping映射器
        • 3.2.1、实例化
          • 3.2.1.1、获取所有拦截器
          • 3.2.1.2、获取所有跨域配置
        • 3.2.2、初始化
          • 3.2.2.1、获取候选bean
          • 3.2.2.2、获取HandlerMethod并统计数量
      • 3.3、RequestMappingHandlerAdapter适配器
        • 3.3.1、实例化
          • 3.3.1.1、获取消息转换器
  • 总结

一、SpringMVC全注解配置

1、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xc.mvc</groupId><artifactId>springmvc</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><dependencies><!-- SpringMVC --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.27</version></dependency><!-- ServletAPI --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!-- Jackson --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.1</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><!--配置Maven中Java的编译版本 --><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build>
</project>

2、web容器初始化类(代替web.xml)

/*** web工程的初始化类,用来代替web.xml* 以下配置的都是以前在web.xml中配置的*/
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {/*** Spring的配置,目前不涉及Spring,这里设置为空*/@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class<?>[0];}/*** SpringMVC的配置*/@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class<?>[]{SpringMVCConfig.class};}/*** 用于配置DispatcherServlet的映射路径*/@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}/*** 注册过滤器*/@Overrideprotected Filter[] getServletFilters() {// 字符编码过滤器CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();characterEncodingFilter.setEncoding("UTF-8");characterEncodingFilter.setForceEncoding(true);// HiddenHttpMethodFilter 用于支持 PUT、DELETE 等 HTTP 请求HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};}
}

3、SpringMVC配置类(代替springmvc.xml)

// 将当前类标识为一个配置类
@Configuration
// 仅仅扫描@Controller、@RestController
@ComponentScan(value = "com.xc",includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, RestController.class})},// 默认扫描 @Component @Repository, @Service, or @ControlleruseDefaultFilters = false 
)
// mvc注解驱动
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {// 拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {MyInterceptor myInterceptor = new MyInterceptor();registry.addInterceptor(myInterceptor).addPathPatterns("/**");}
}

拦截器

public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("处理器方法前调用");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("处理器方法后调用");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("渲染完成后调用");}
}

4、测试Controller

// 接受User对象修改并返回
@PostMapping("/test")
@ResponseBody
public User test(@RequestBody User user) {// 修改名字为李四然后返回给前台user.setName("李四");System.out.println(user);return user;
}

启动tomcat发送请求结果

在这里插入图片描述

二、SpringServletContainerInitializer

1、web容器初始化入口

  • 在web容器启动时为提供给第三方组件机会做一些初始化的工作,例如注册servlet或者filtes等
    • servlet规范中通过ServletContainerInitializer接口实现此功能
  • 需要在对应的jar包的META-INF/services目录创建一个名为javax.servlet.ServletContainerInitializer的文件
    • 文件内容指定具体的ServletContainerInitializer实现类

在这里插入图片描述

ps:JDK会自动加载META-INF/services目录下的类(深入理解SPI机制)
容器在启动应用的时候,会扫描当前应用每一个jar包里面META-INF/services指定的实现类(tomcat默认读取)

2、SpringServletContainerInitializer的作用解析

  • @HandlesTypes注解作用
    • 获取到所有的实现了WebApplicationInitializer接口的类,然后赋值给onStartup方法的webAppInitializerClasses参数
    • 官方话术为,获取当前类(SpringServletContainerInitializer)感兴趣的类(WebApplicationInitializer)信息
  • 获取到WebApplicationInitializer实现类的Class集合,反射创建对象,遍历调用对象的onStartup方法
// SpringServletContainerInitializer类
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {@Overridepublic void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)throws ServletException {List<WebApplicationInitializer> initializers = Collections.emptyList();// 如果找不到WebApplicationInitializer的实现类,webAppInitializerClasses就为nullif (webAppInitializerClasses != null) {initializers = new ArrayList<>(webAppInitializerClasses.size());for (Class<?> waiClass : webAppInitializerClasses) {// 判断实现类不是接口抽象类,即正常的接口实现类if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&WebApplicationInitializer.class.isAssignableFrom(waiClass)) {try {// 反射创建对象,并添加到集合中,后面统一遍历调用onStartup方法initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass).newInstance());}catch (Throwable ex) {throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);}}}}// 集合为空,证明没找到实现类,直接返回if (initializers.isEmpty()) {servletContext.log("No Spring WebApplicationInitializer types detected on classpath");return;}// 排序,证明WebApplicationInitializer的实现类有先后顺序AnnotationAwareOrderComparator.sort(initializers);for (WebApplicationInitializer initializer : initializers) {// 调用WebApplicationInitializer接口实现类的onStartup方法initializer.onStartup(servletContext);}}
}// WebApplicationInitializer接口
public interface WebApplicationInitializer {/*** 初始化此Web应用程序所需的任何Servlet、过滤器、侦听器上下文参数和属性配置给定的ServletContext*/void onStartup(ServletContext servletContext) throws ServletException;
}

WebApplicationInitializer接口与自定义配置类WebAppInitalizer(代替web.xml)关系

  • WebApplicationInitializer初始化核心接口,onStartup方法初始化Servelt、过滤器等
  • WebAppInitalizer即为WebApplicationInitializer的实现类,也就是SpringServletContainerInitializer要找的感兴趣的类,获取到多个放到集合initializer中,然后排序,最后遍历调用onStartup方法

在这里插入图片描述

  总结SpringServletContainerInitializer作用:加载自定义的WebApplicationInitializer初始化核心接口的实现类WebAppInitializer,调用onStartup方法来实现web容器初始化。

在这里插入图片描述

三、自定义配置类的加载

自定义配置类WebAppInitializer(代替web.xml)的类图如下:

在这里插入图片描述
  由上一节可知,web容器初始化工作会调用自定义配置类的onStartup方法,那就是根据类图从下往上找onStartup方法调用,WebAppInitializer和AbstractAnnotationConfigDispatcherServletInitializer中都没有onStartup方法,那么首先进入AbstractDispatcherServletInitializer重写的onStartup方法,核心内容注册前端控制器

在这里插入图片描述

1、AbstractDispatcherServletInitializer注册前端控制器

  • getServletMappings():调用自定义配置类配置DispatcherServlet的映射路径的方法
  • getServletFilters():调用自定义配置类注册过滤器的方法
// AbstractDispatcherServletInitializer类的方法
protected void registerDispatcherServlet(ServletContext servletContext) {// 获取servlet名称,常量“dispatcher”String servletName = getServletName();// 创建一个web应用程序子容器WebApplicationContext servletAppContext = createServletApplicationContext();// 创建DispatcherServlet对象,将上下文设置到dispatcherServlet中FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);// 设置servlet容器初始化参数(这里不设置一般默认为null)dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());// 把servlet添加到Tomcat容器中ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);if (registration == null) {throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +"Check if there is another servlet registered under the same name.");}// 将前端控制器初始化提前到服务器启动时,否则调用时才会初始化registration.setLoadOnStartup(1);// 添加servlet映射,拦截请求// 调用自定义配置类重写的getServletMappings方法registration.addMapping(getServletMappings());// 设置是否支持异步,默认trueregistration.setAsyncSupported(isAsyncSupported());// 获取所有的过滤器getServletFilters方法// 调用自定义配置类重写的getServletMappings方法Filter[] filters = getServletFilters();if (!ObjectUtils.isEmpty(filters)) {for (Filter filter : filters) {registerServletFilter(servletContext, filter);}}// 空方法,可以再对dispatcherServlet进行处理customizeRegistration(registration);
}

1.1、创建web注解容器

  • getServletConfigClasses():调用自定义配置类配置SpringMVC配置的方法
// AbstractAnnotationConfigDispatcherServletInitializer类方法
protected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();// 调用自定义配置类的设置子容器配置文件的方法Class<?>[] configClasses = getServletConfigClasses();if (!ObjectUtils.isEmpty(configClasses)) {context.register(configClasses);}return context;
}

1.2、创建DispatcherServlet对象

  • 创建DispatcherServlet对象,传入web容器
// AbstractDispatcherServletInitializer类方法
protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {return new DispatcherServlet(servletAppContext);
}

1.3、注册过滤器

  • 将过滤器添加到Tomcat容器的过滤器集合中
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {String filterName = Conventions.getVariableName(filter);Dynamic registration = servletContext.addFilter(filterName, filter);...registration.setAsyncSupported(isAsyncSupported());registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());return registration;
}
  • 对于注册过滤器是Tomcat的内容,之前文章Tomcat源码解析(五):StandardEngine、StandardHost、StandardContext、StandardWrapper中有介绍

在这里插入图片描述

小结一下

  • 目前为止代替web.xml的配置类中内容加载完成
    • 创建web注解容器,此时只是创建出来,还没有初始化
    • 创建DispatcherServlet并设置映射路径
    • 注册过滤器
  • 接下来的入口在DispatcherServlet这里,因为其本质是Servlet,那么就会涉及到Tomcat初始化Servelt

2、DispatcherServlet初始化

DispatcherServlet类图如下:

在这里插入图片描述

  Tomcat启动容器加载Servelt(这里是DispatcherServlet)并初始化,就会调用到这里。之前文章Tomcat源码解析(五):StandardEngine、StandardHost、StandardContext、StandardWrapper中有介绍。

在这里插入图片描述

  • initWebApplicationContext方法内核心内容就是调用configureAndRefreshWebApplicationContext这个方法
  • 看这方法名字中文直译:配置和刷新web容器
  • 核心内容就是最后一句,web容器的刷新

在这里插入图片描述

  • 容器刷新抽象类AbstractApplicationContextrefresh方法,看过spring源码的应该很熟悉
  • web容器spring容器都间接继承了AbstractApplicationContext,容器刷新都调用如下方法
  • 关于spring的源码Spring源码解析(三):bean容器的刷新之前介绍

在这里插入图片描述

  容器初始化时候有个很重要的bean工厂后置处理器ConfigurationClassPostProcessor,作用就是解析@Configuration,@Import,@ComponentScan,@Bean等注解给bean容器添加bean定义,之前文章Spring源码解析(六):bean工厂后置处理器ConfigurationClassPostProcessor有介绍。

  接下来的入口就在自定义g配置类SpringMVCConfi这里,因为它的配置类注解@Configuration(也是@Component),@ComponentScan(扫描@Controller注解)@EnableWebMvc(导入DelegatingWebMvcConfiguration.class)注解都会被扫描解析到。

在这里插入图片描述

四、@EnableWebMvc解析

@EnableWebMvc

在这里插入图片描述

1、WebMvcConfigurer接口

  在讲DelegatingWebMvcConfiguration之前先说下WebMvcConfigurer接口,因为下面内容都是围绕着WebMvcConfigurer接口展开的。

  WebMvcConfigurer是一个接口,它提供了一种扩展SpringMVC配置的方式。通过实现WebMvcConfigurer接口,可以定制化SpringMVC的配置例如添加拦截器、资源处理、视图解析器等。

public interface WebMvcConfigurer {...// 配置拦截器default void addInterceptors(InterceptorRegistry registry) {}// 配置跨域default void addCorsMappings(CorsRegistry registry) {}// 配置视图解析器default void configureViewResolvers(ViewResolverRegistry registry) {}// 配置消息转换器(此时可能还没有转换器)default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}// 扩展消息转换器(至少已存在默认转换器)default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}// 配置异常处理器default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}...
}

2、DelegatingWebMvcConfiguration

DelegatingWebMvcConfiguration的类图如下:
在这里插入图片描述

  • 如果开发者或者第三方想要配置拦截器、消息转换器的等配置,只要实现WebMvcConfigurer接口重写对应方法即可
  • 通过setConfigurers方法讲所有WebMvcConfigurer接口实现类注入进来,放入configurers的List<WebMvcConfigurer> delegates属性中
  • 下面会讲到什么时候触发调用DelegatingWebMvcConfiguration中重写的MVC配置方法
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {// WebMvcConfigurerComposite实现WebMvcConfigurer,内部有个WebMvcConfigurer集合private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();// 注入一组WebMvcConfigurer,这些WebMvcConfigurer由开发人员提供,或者框架其他部分提供@Autowired(required = false)public void setConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);}}...// 如下方法都是重写父类WebMvcConfigurationSupport// 与WebMvcConfigurer接口中的方法一样,配置拦截器、跨域配置等@Overrideprotected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {this.configurers.configureDefaultServletHandling(configurer);}@Overrideprotected void addInterceptors(InterceptorRegistry registry) {this.configurers.addInterceptors(registry);}@Overrideprotected void addCorsMappings(CorsRegistry registry) {this.configurers.addCorsMappings(registry);}@Overrideprotected void configureViewResolvers(ViewResolverRegistry registry) {this.configurers.configureViewResolvers(registry);}@Overrideprotected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {this.configurers.configureMessageConverters(converters);}@Overrideprotected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {this.configurers.configureHandlerExceptionResolvers(exceptionResolvers);}...
}

  调用DelegatingWebMvcConfiguration重写的MVC配置方法实际就是对应的配置添加到对应的注册器中。如所有的拦截器都会被添加到InterceptorRegistry(拦截器注册器)、所有跨域配置则会被添加到CorsRegistry(跨域注册器),不用说对应的注册器中肯定维护着对应的配置集合。

// WebMvcConfigurerComposite类
class WebMvcConfigurerComposite implements WebMvcConfigurer {private final List<WebMvcConfigurer> delegates = new ArrayList<>();@Overridepublic void addInterceptors(InterceptorRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.addInterceptors(registry);}}@Overridepublic void addCorsMappings(CorsRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.addCorsMappings(registry);}}@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.configureViewResolvers(registry);}}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {for (WebMvcConfigurer delegate : this.delegates) {delegate.configureMessageConverters(converters);}}
}

3、WebMvcConfigurationSupport

  在上面说到WebMvcConfigurationSupport类中定义了与WebMvcConfigurer接口一样的配置方法,都是空实现,由子类DelegatingWebMvcConfiguration重写,遍历所有WebMvcConfigurer的实现类,将对应配置添加到对应注册器中。

  另外一方面在WebMvcConfigurationSupport类中有很多@Bean方法,即bean定义,返回值即为创建的bean对象。其中有两个很重要,映射器RequestMappingHandlerMapping适配器RequestMappingHandlerAdapter

3.1、处理器映射器和处理器适配器

映射器HandlerMapping

  • HandlerMapping映射器作用:主要是根据request请求匹配/映射上能够处理当前request的Handler
  • 定义Handler的方式有很多
    • 最常用的@Controller,结合@RequestMapping("/test")
    • 实现Controller接口,实现handleRequest方法,结合@Component(“/test”)
    • 实现HttpRequestHandler接口,实现handleRequest方法,结合@Component(“/test”)
  • 以上三种方式都需要生成请求和Handler的映射
    • 所以抽象出一个接口:HandlerMapping,有很多实现类
    • @RequestMapping注解的Handler使用RequestMappingHandlerMapping处理
    • 其他方式会使用BeanNameUrlHandlerMapping、SimpleUrlHandlerMapping

适配器HandlerAdapter

  • 上一步中不同映射器通过请求映射到的Handler不确定类型
    • @RequestMapping注解方式获取到的是具体的Method
    • 其他实现接口方式获取到的是具体的Class
  • 此时拿到Handler去执行具体的方法时候,方式是不统一
  • 那么适配器就出现了
  • RequestMappingHandlerAdapter就是处理@RequestMapping注解的Handler

3.2、RequestMappingHandlerMapping映射器

  • 一句话解释它:解析@RequestMapping注解
3.2.1、实例化
// WebMvcConfigurationSupport类方法
@Bean
@SuppressWarnings("deprecation")
public RequestMappingHandlerMapping requestMappingHandlerMapping(@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,@Qualifier("mvcConversionService") FormattingConversionService conversionService,@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {// 创建RequestMappingHandlerMapping对象RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();mapping.setOrder(0);// 设置所有的拦截器,并排序mapping.setInterceptors(getInterceptors(conversionService, resourceUrlProvider));mapping.setContentNegotiationManager(contentNegotiationManager);// 设置所有的跨域配置mapping.setCorsConfigurations(getCorsConfigurations());// 省略各种匹配url的属性,如url正则匹配等等,我们这次只考虑url正常匹配...return mapping;
}
3.2.1.1、获取所有拦截器

  这里先创建拦截器注册器InterceptorRegistry,然后调用DelegatingWebMvcConfiguration重写WebMvcConfigurationSupport的添加拦截器方法addInterceptors,这样所有拦截器就都会被添加到InterceptorRegistry registry中。

// WebMvcConfigurationSupport
protected final Object[] getInterceptors(FormattingConversionService mvcConversionService,ResourceUrlProvider mvcResourceUrlProvider) {if (this.interceptors == null) {InterceptorRegistry registry = new InterceptorRegistry();// 这里就是调用DelegatingWebMvcConfiguration重写的方法addInterceptors(registry);registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService));registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider));this.interceptors = registry.getInterceptors();}return this.interceptors.toArray();
}
3.2.1.2、获取所有跨域配置

  也是先创建跨域注册器CorsRegistry,然后调用然后调用DelegatingWebMvcConfiguration重写WebMvcConfigurationSupport的添加跨域方法addCorsMappings,也是添加到CorsRegistry registry中。

// WebMvcConfigurationSupport
protected final Map<String, CorsConfiguration> getCorsConfigurations() {if (this.corsConfigurations == null) {CorsRegistry registry = new CorsRegistry();addCorsMappings(registry);this.corsConfigurations = registry.getCorsConfigurations();}return this.corsConfigurations;
}
3.2.2、初始化

RequestMappingHandlerMapping的复杂类图看一下(有删减)

  @RequestMapping注解肯定是在容器启动时候解析的,那么这个工作就放在RequestMappingHandlerMapping这个bean对象的初始化阶段来完成。之前文章Spring源码解析(四):单例bean的创建流程有介绍过,bean对象创建后会调用各种初始化方法,其实就包括调用InitializingBean接口afterPropertiesSet方法来实现初始化

在这里插入图片描述

  • RequestMappingHandlerMapping实现了afterPropertiesSet方法如下
// RequestMappingHandlerMapping类方法
@Override
@SuppressWarnings("deprecation")
public void afterPropertiesSet() {// 创建RequestMappingInfo对象this.config = new RequestMappingInfo.BuilderConfiguration();this.config.setTrailingSlashMatch(useTrailingSlashMatch());this.config.setContentNegotiationManager(getContentNegotiationManager());if (getPatternParser() != null) {this.config.setPatternParser(getPatternParser());Assert.isTrue(!this.useSuffixPatternMatch && !this.useRegisteredSuffixPatternMatch,"Suffix pattern matching not supported with PathPatternParser.");}else {this.config.setSuffixPatternMatch(useSuffixPatternMatch());this.config.setRegisteredSuffixPatternMatch(useRegisteredSuffixPatternMatch());this.config.setPathMatcher(getPathMatcher());}// 调用父类实现的afterPropertiesSet方法super.afterPropertiesSet();
}
  • 父类AbstractHandlerMethodMapping实现了afterPropertiesSet方法如下
// AbstractHandlerMethodMapping类方法/*** 在初始化时检测处理程序方法*/
@Override
public void afterPropertiesSet() {initHandlerMethods();
}/*** 扫描 ApplicationContext 中的 Bean,检测并注册处理程序方法*/
protected void initHandlerMethods() {// 获取所有的bean对象并遍历for (String beanName : getCandidateBeanNames()) {if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {// 筛选候选的beanprocessCandidateBean(beanName);}}// getHandlerMethods()获取请求路径与具体Controller方法的映射关系handlerMethodsInitialized(getHandlerMethods());
}
3.2.2.1、获取候选bean
// AbstractHandlerMethodMapping类方法
protected void processCandidateBean(String beanName) {Class<?> beanType = null;try {// 获取bean对象的Class类型beanType = obtainApplicationContext().getType(beanName);}catch (Throwable ex) {...}// 判断是否处理程序if (beanType != null && isHandler(beanType)) {// 查找处理程序的方法detectHandlerMethods(beanName);}
}
  • 根据类上@Controller@RequestMapping注解判断是否为处理程序
// RequestMappingHandlerMapping
@Override
protected boolean isHandler(Class<?> beanType) {return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}
  • 查询处理程序的方法
    1. 此时获取到的handler已经确定有@Controller或者@RequestMapping
    2. 遍历handler类下所有的Method
      • 判断Method方法上是否有@RequestMapping注解
      • 有注解则将注解内的属性包装成一个类:RequestMappingInfo
    3. 返回一个map集合methods
      • key为有@RequestMapping注解的Method对象
      • value为RequestMappingInfo对象
// AbstractHandlerMethodMapping类方法
protected void detectHandlerMethods(Object handler) {Class<?> handlerType = (handler instanceof String ?obtainApplicationContext().getType((String) handler) : handler.getClass());if (handlerType != null) {// 类如果被代理,获取真正的类型Class<?> userType = ClassUtils.getUserClass(handlerType);Map<Method, T> methods = MethodIntrospector.selectMethods(userType,(MethodIntrospector.MetadataLookup<T>) method -> {try {return getMappingForMethod(method, userType);}catch (Throwable ex) {...}});...		// 这里有做了一些列的包装处理methods.forEach((method, mapping) -> {Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);registerHandlerMethod(handler, invocableMethod, mapping);});}
}

我简述下获取到methods以后的的包装处理,就是各种包装对象,就不放代码了,没啥意思

  • 首先创建一个MappingRegistry(映射注册器),以后的mapping映射什么都放这里
  • handler(也就是Controller类对象)和有@RequestMapping的Method组成对象HandlerMethod
  • 获取到HandlerMethod后,这时候会校验RequestMappingInfo(@RequestMapping属性对象)是否存在
    • 存在的话这里就会抛出异常There is already 'xxx' bean method(这个大家应该很熟悉)
  • 最后一步往MappingRegistryMap<T, MappingRegistration<T>> registry属性中注册内容
    • key为RequestMappingInfo对象(@RequestMapping注解属性,包括映射路径)
    • value为由RequestMappingInfo和HandlerMethod组成的新对象MappingRegistration
  • 注意:以上步骤都是在readWriteLock锁内完成的,以防多个线程注册映射对象重复
3.2.2.2、获取HandlerMethod并统计数量
  • 从mappingRegistry中获取map集合,key为RequestMappingInfo,value为HandlerMethod
// AbstractHandlerMethodMapping类方法
public Map<T, HandlerMethod> getHandlerMethods() {this.mappingRegistry.acquireReadLock();try {return Collections.unmodifiableMap(this.mappingRegistry.getRegistrations().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().handlerMethod)));}finally {this.mappingRegistry.releaseReadLock();}
}
  • 获取到上面拿到的handlerMethods,打印数量
protected void handlerMethodsInitialized(Map<T, HandlerMethod> handlerMethods) {// 获取到上面拿到的值,打印数量int total = handlerMethods.size();if ((logger.isTraceEnabled() && total == 0) || (logger.isDebugEnabled() && total > 0) ) {logger.debug(total + " mappings in " + formatMappingName());}
}

3.3、RequestMappingHandlerAdapter适配器

  • 一句话解释它:拿到RequestMappingHandlerMapping解析出的HandlerMethod去调用具体的Method
3.3.1、实例化
// WebMvcConfigurationSupport类方法private static final boolean jackson2Present;
// 加载对应的类,能加载成功方true,不能加载成功,表示没有这个类,没有导入包,返回false
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,@Qualifier("mvcConversionService") FormattingConversionService conversionService,@Qualifier("mvcValidator") Validator validator) {// 创建RequestMappingHandlerAdapter对象RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();adapter.setContentNegotiationManager(contentNegotiationManager);// 设置消息转换器adapter.setMessageConverters(getMessageConverters());adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer(conversionService, validator));adapter.setCustomArgumentResolvers(getArgumentResolvers());adapter.setCustomReturnValueHandlers(getReturnValueHandlers());// 请求响应数据与json的转化// 如果导入Jackson包,添加if (jackson2Present) {adapter.setRequestBodyAdvice(Collections.singletonList(new JsonViewRequestBodyAdvice()));adapter.setResponseBodyAdvice(Collections.singletonList(new JsonViewResponseBodyAdvice()));}// 省略异步配置,以后再研究...return adapter;
}
3.3.1.1、获取消息转换器

  先调用DelegatingWebMvcConfiguration重写的方法,也就是遍历所有WebMvcConfigurer实现类,调用他们的configureMessageConverters方法,新增的消息转换器都会添加到messageConverters集合中。如果开发者和第三方都没有添加,那么设置默认的消息转换器,设置完以后,再调用扩展方法,也就是遍历所有WebMvcConfigurer实现类,调用他们的extendMessageConverters方法,对消息转换器做最后修改

// WebMvcConfigurationSupport
protected final List<HttpMessageConverter<?>> getMessageConverters() {if (this.messageConverters == null) {this.messageConverters = new ArrayList<>();// 这里就是调用DelegatingWebMvcConfiguration重写的方法,配置消息转换器configureMessageConverters(this.messageConverters);if (this.messageConverters.isEmpty()) {// 如果上面没有添加消息转换器,这里添加默认的消息转换器addDefaultHttpMessageConverters(this.messageConverters);}// 这里就是调用DelegatingWebMvcConfiguration重写的方法,扩展消息转化器extendMessageConverters(this.messageConverters);}return this.messageConverters;
}

  加载jackson里的类,能加载成功jackson2Present返回true,不能加载成功,表示没有这个类,没有导入包,返回jackson2Present返回false,然后去判断是否导入Google、JDK自带的处理JSON类。一般我们会导入Jackson,那么这里会添加MappingJackson2HttpMessageConverter消息转换器。

// WebMvcConfigurationSupport类方法
protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {messageConverters.add(new ByteArrayHttpMessageConverter());messageConverters.add(new StringHttpMessageConverter());messageConverters.add(new ResourceHttpMessageConverter());messageConverters.add(new ResourceRegionHttpMessageConverter());...// jacksonif (jackson2Present) {Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();if (this.applicationContext != null) {builder.applicationContext(this.applicationContext);}messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));}// Google Gson 库中的一个核心类,Java对象与JSON 格式字符串进行相互转换else if (gsonPresent) {messageConverters.add(new GsonHttpMessageConverter());}// JDK 类库JSON类else if (jsonbPresent) {messageConverters.add(new JsonbHttpMessageConverter());}...
}

总结

  • 加载继承AbstractAnnotationConfigDispatcherServletInitializer的MVC配置类(开发者创建,代替web.xml)
  • 既然代替web.xml那么这个配置类可以设置DispatcherServlet的映射路径注册过滤器
  • 父类AbstractAnnotationConfigDispatcherServletInitializer里面会创建web注解容器创建DispatcherServlet对象添加过滤器到Tomcat容器的过滤器集合中
    • DispatcherServlet初始化触发了web容器的刷新,加载所有@Controller注解的bean
  • 如果开发者或者第三方想要配置拦截器消息转换器的等配置,只要实现WebMvcConfigurer接口重写对应方法即可
  • 解析@RequestMapping注解
    • 遍历所有的bean,筛选类上是否有@Controller@RequestMapping注解
    • 如果有,再遍历所有的方法,筛选方法上是否有@RequestMapping注解
    • 最后包装成map存起来
      • key为@RequestMapping注解属性组成的RequestMappingInfo
      • value为Controller里存在@RequestMapping注解的Method组成的HandlerMethod

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1474957.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

【人工智能】-- 智能家居

个人主页&#xff1a;欢迎来到 Papicatch的博客 课设专栏 &#xff1a;学生成绩管理系统 专业知识专栏&#xff1a; 专业知识 文章目录 &#x1f349;引言 &#x1f349;基于深度卷积神经网络的表情识别 &#x1f348;流程图 &#x1f348;模型设计 &#x1f34d;网络架…

大厂面试官问我:Redis缓存如果扛不住,该怎么办?【后端八股文十一:Redis缓存八股文合集(1)】

本文为【Redis分布式锁八股文合集&#xff08;2&#xff09;】初版&#xff0c;后续还会进行优化更新&#xff0c;欢迎大家关注交流~ hello hello~ &#xff0c;这里是绝命Coding——老白~&#x1f496;&#x1f496; &#xff0c;欢迎大家点赞&#x1f973;&#x1f973;关注&…

C++ | Leetcode C++题解之第22题完全二叉树的节点个数

题目&#xff1a; 题解&#xff1a; class Solution { public:int countNodes(TreeNode* root) {if (root nullptr) {return 0;}int level 0;TreeNode* node root;while (node->left ! nullptr) {level;node node->left;}int low 1 << level, high (1 <&…

三级_网络技术_08_IP地址规划技术

1.如果内网的某Web服务器允许外网访问&#xff0c;并且该服务器NAT转换表如图所示&#xff0c;那么外网主机正确访问该服务器时使用的URL是()。 http://59.12.1.1:1423 http://135.2.2.1 http://135.2.2.1:5511 http://192.168.33.11:80 2.如果内网的某FTP服务器允许外网访…

基于大数据技术Hadoop的气象分析可视化大屏设计和实现

博主介绍&#xff1a;硕士研究生&#xff0c;专注于信息化技术领域开发与管理&#xff0c;会使用java、标准c/c等开发语言&#xff0c;以及毕业项目实战✌ 从事基于java BS架构、CS架构、c/c 编程工作近16年&#xff0c;拥有近12年的管理工作经验&#xff0c;拥有较丰富的技术架…

网络资源模板--Android Studio 外卖点餐App

目录 一、项目演示 二、项目测试环境 三、项目详情 四、完整的项目源码 原创外卖点餐&#xff1a;基于Android studio 实现外卖(点)订餐系统 非原创奶茶点餐&#xff1a;网络资源模板--基于 Android Studio 实现的奶茶点餐App报告 一、项目演示 网络资源模板--基于Android …

vb.netcad二开自学笔记6:第一个绘制线段命令

.net编写绘制直线已完全不同于ActiveX的&#xff08;VBA&#xff09;的方式&#xff0c;过程更类似于arx程序&#xff0c;需要通过操作AutoCAD 数据库添加对象&#xff01;下面的代码是在以前代码基础上添加了一个新myline命令。 AutoCAD 数据库结构 myline命令代码 Imports A…

Unity AssetsBundle 详解

文章目录 1.AssetBundle 概念2.AssetBundle 优势3.AssetBundle 特性4.AssetBundle 使用流程4.1 分组4.2 打包4.3 加载包4.4 加载资源4.5 卸载资源 5.AssetBundleManifest6.AssetBundle的内存占用7.AB包资源加密 1.AssetBundle 概念 AssetBundle又称AB包&#xff0c;是Unity提供…

hadoop分布式中某个 节点报错的解决案例

前言 在分布式节点中&#xff0c;发现有个节点显示不可用状态&#xff0c;因此需要紧急修复。 hadoop版本 目前这套集群hadoop的版本如下&#xff1a; 集群报错详细日志&#xff1a; 1/1 local-dirs are bad: /kkb/install/hadoop-2.6.0-cdh5.14.2/hadoopDatas/tempDatas/n…

服务器本地部署文件服务器minio

minio类似于阿里云的OSS&#xff0c;为不方便把图、文、日志等形式的文件保存在公有云上的&#xff0c;可以在自己的服务器上部署文件服务器 看过本人前几个文章的&#xff0c;使用docker就会很快上手部署&#xff0c;直接上所有代码 #添加镜像 docker search minio docker p…

python - 文件 / 永久存储:pickle / 异常处理

一.文件 利用help(open)可以看到open()函数的定义&#xff1a; >>> help(open) Help on built-in function open in module _io:open(file, moder, buffering-1, encodingNone, errorsNone, newlineNone, closefdTrue, openerNone) 默认打开模式是’rt’&#xff0…

【网络安全】实验三(基于Windows部署CA)

一、配置环境 打开两台虚拟机&#xff0c;并参照下图&#xff0c;搭建网络拓扑环境&#xff0c;要求两台虚拟的IP地址要按照图中的标识进行设置&#xff0c;并根据搭建完成情况&#xff0c;勾选对应选项。注&#xff1a;此处的学号本人学号的最后两位数字&#xff0c;1学号100…

逆袭707计划

暑假沉淀计划707 上午&#xff1a; 早起习惯&#xff1a;先打开idea将昨日所学代码敲一遍&#xff08;预估半小时&#xff09; 早饭时间可并发查看是否有自媒体商单 学习一节JavaEE课程&#xff08;预估一个半小时&#xff09; 完成对应的作业&#xff08;预估一个小时&am…

Python28-9 XGBoost算法

XGBoost&#xff08;eXtreme Gradient Boosting&#xff0c;其正确拼写应该是 "Extreme Gradient Boosting"&#xff0c;而XGBoost 的作者在命名时故意使用了不规范的拼写&#xff0c;将“eXtreme”中的“X”大写&#xff0c;以突出其极限性能和效率&#xff09;是一…

【python学习】快速了解python基本数据类型

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏: 《C干货基地》《粉丝福利》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 文章目录 前言1. 整数&#xff08;int&#xff09;2. 浮点数&#xff08;float&#xff09;3. 布尔值&#xff08;bool&#xf…

WPS+Python爬取百度之星排名

运行效果 手动拉取 https://www.matiji.net/exam/contest/contestdetail/146 如果手动查找&#xff0c;那么只能通过翻页的方式&#xff0c;每页10行&#xff08;外加一行自己&#xff09;。 爬取效果预览 本脚本爬取了个人排名和高校排名&#xff0c;可以借助WPS或MS Offi…

前端web在线PPT编辑器-PPTLIST

哈喽&#xff0c;大家好&#xff0c;今天给大家介绍一款的在线的PPT编辑器开源框架-PPTLIST&#xff1b;他是一个基于 Vue3.x TypeScript 的在线演示文稿&#xff08;幻灯片&#xff09;应用&#xff0c;还原了大部分 Office PowerPoint 常用功能&#xff0c;支持 文字、图片、…

【ffmpeg系列一】源码构建,ubuntu22与win10下的过程对比。

文章目录 背景ubuntu22结论 win10过程 对比结论 背景 顺手编译个ffmpeg试试&#xff0c;看看不同平台下谁的配置比较繁琐。 先让gpt给出个教程&#xff1a; ubuntu22 使用elementary-os7.1构建&#xff0c;看看有几个坑要踩。 错误1&#xff1a; 依赖libavresample-dev未…

明日周刊-第15期

赶在周末结束前输出一把&#xff0c;周日的晚上大家要睡个好觉哦。 文章目录 一周热点资源分享言论歌曲推荐 一周热点 科技创新与基础设施建设 深中通道正式通车试运营 时间&#xff1a;6月30日 内容&#xff1a;国家重大工程深中通道正式通车试运营&#xff0c;标志着珠江口东…