我們先理簡單梳理一個關系
關系梳理
- spring ioc 是spring的核心,用來管理spring bean的生命周期
- MVC 是一種使用 MVC(Model View Controller 模型-視圖-控制器)設計創建 Web 應用程序的模式
- spring mvc 是spring的一個獨立的模塊,就像AOP一樣
在spring mvc中把web框架和spring ioc融合在一起,是通過ContextLoaderListener監聽servlet上下文的創建后來加載父容器完成的,然后通過配置一個servlet對象DispatcherServlet,在初始化DispatcherServlet時來加載具體子容器,詳細的可以參考spring ioc & web宿主 這篇文章
關於我們今天要講的RequestMappingHandlerMapping也是在DispatcherServlet的初始化過程中自動加載的,默認會自動加載所有實現HandlerMapping接口的bean,且我們可以通過serOrder來設置優先級,系統默認會加載RequestMappingHandlerMapping、BeanNameUrlHandlerMapping、SimpleUrlHandlerMapping 並且按照順序使用
1private void initHandlerMappings(ApplicationContext context) {
2 this.handlerMappings = null;
3 if (this.detectAllHandlerMappings) {
4 // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
5 Map<String, HandlerMapping> matchingBeans =
6 BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
7 if (!matchingBeans.isEmpty()) {
8 this.handlerMappings = new ArrayList<>(matchingBeans.values());
9 // We keep HandlerMappings in sorted order.
10 AnnotationAwareOrderComparator.sort(this.handlerMappings);
11 }
12 }
13}
RequestMappingHandlerMapping 加載過程
- RequestMappingHandlerMapping 實現了接口InitializingBean,在bean加載完成后會自動調用afterPropertiesSet方法,在此方法中調用了initHandlerMethods()來實現初始化
- 遍歷所有bean,如果bean實現帶有注解@Controller或者@RequestMapping 則進一步調用detectHandlerMethods處理,處理邏輯大致就是根據@RequestMapping配置的信息,構建RequestMappingInfo,然后注冊到MappingRegistry中
1protected void initHandlerMethods() {
2 String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
3 BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
4 obtainApplicationContext().getBeanNamesForType(Object.class));
5 for (String beanName : beanNames) {
6 if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
7 Class<?> beanType = null;
8 beanType = obtainApplicationContext().getType(beanName);
9 if (beanType != null && isHandler(beanType)) {
10 detectHandlerMethods(beanName);
11 }
12 }
13 }
14 handlerMethodsInitialized(getHandlerMethods());
15 }
1protected void detectHandlerMethods(final Object handler) {
2 Class<?> handlerType = (handler instanceof String ?
3 obtainApplicationContext().getType((String) handler) : handler.getClass());
4 if (handlerType != null) {
5 final Class<?> userType = ClassUtils.getUserClass(handlerType);
6 Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
7 (MethodIntrospector.MetadataLookup<T>) method -> {
8 try {
9 return getMappingForMethod(method, userType);
10 }
11 catch (Throwable ex) {
12 throw new IllegalStateException("Invalid mapping on handler class [" +
13 userType.getName() + "]: " + method, ex);
14 }
15 });
16 methods.forEach((method, mapping) -> {
17 Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
18 registerHandlerMethod(handler, invocableMethod, mapping);
19 });
20 }
21 }
RequestMappingHandlerMapping 解析過程
- 在DispatcherServlet中,根據請求對象調用getHander方法獲取HandlerExecutionChain對象
- 在getHander方法中也是遍歷上面默認加載的三個HandlerMapping,當然第一個就是RequestMappingHandlerMapping對象,調用其getHandler方法,根據請求path,找到一個最為匹配的HandlerMethod來處理請求
1protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
2 if (this.handlerMappings != null) {
3 for (HandlerMapping hm : this.handlerMappings) {
4 if (logger.isTraceEnabled()) {
5 logger.trace(
6 "Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
7 }
8 HandlerExecutionChain handler = hm.getHandler(request);
9 if (handler != null) {
10 return handler;
11 }
12 }
13 }
14 return null;
15 }
- 根據請求路徑獲取HandlerInterceptor,然后和上面獲得的HandlerMethod一起構成HandlerExecutionChain返回給DispatcherServlet
DispatcherServlet得到HandlerExecutionChain也就獲得了處理此次請求所需的Handler【即我們熟悉的Controller和對應的Action】,后續將會選擇合適HandlerAdapter來執行對應的Handler,獲取返回值,再根據返回值類型,進一步覺決定用什么方式展示給用戶,下一遍將開啟HandlerAdapter的講解…….
微信公眾號:宋坤明
更多精彩請參考 完整版系列 也可以直接關注我
圖注:宋坤明公眾號
