spring mvc源码分析

springmvc主线的重点在于两个类:

1.请求统一处理入口servlet:

org.springframework.web.servlet.DispatcherServlet

2.@RequestMapping注解解析并生成URL映射类,DispatcherServlet在找controller时用到:

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

DispatcherServlet

统一处理请求的入口,一个servlet,既然是servlet,那么就要配置到web容器中。

从前的xml配置方式如下,url-pattern配置想要springmvc处理的请求后缀,contextConfigLocation作为springmvc创建的ApplicationContext配置文件,通常配置mvc相关的拦截器,视图渲染,参数转换等:

 

 

 servlet配置好了之后,请求会走到org.springframework.web.servlet.DispatcherServlet#doDispatch方法:

 

 

 

 

handlerAdaper的执行,返回ModelAndView视图

 

 

 

 

 主线逻辑很简单也很清晰,下面我们分讲下每一步的具体细节。

handlerMappings从哪里来

如下方法加载获取:org.springframework.web.servlet.DispatcherServlet#initHandlerMappings

方法内容也很简单,就是从ApplicationContext获取HandlerMapping.class类型的bean,那么问题来了,我们上面提到的关键类RequestMappingHandlerMapping是什么时候放到context中的呢?

 

 

 从前的xml配置中有个标签mvc:annotation-driven,spring中的自定义标签通过下图中的文件配置对应的处理类

具体内容如下,mvc标签由org.springframework.web.servlet.config.MvcNamespaceHandler处理:

 

 

 

 

 

 

 我们关注的annotation-driven由org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser解析:

 当然,也可以通过注解EnableWebMvc来加载RequestMappingHandlerMapping,

@Import对应的是一个configuration配置类org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration

 

 DelegatingWebMvcConfiguration父类org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport都是关于mvc的配置bean,其中就包含RequestMappingHandlerMapping

 

 spring boot自动配置spring mvc见另一篇博文。

 

posted on 2019-06-05 08:54  砌码匠人  阅读(99)  评论(0)    收藏  举报

导航