1. 程式人生 > >SpringMVC原始碼之Handler註冊、獲取以及請求controller中方法

SpringMVC原始碼之Handler註冊、獲取以及請求controller中方法

#### 總結 1. 對requestMappingHandlerMapping進行initializeBean時register Handler 2. http開始請求時,initHandlerMappings,DispatcherServlet 中handlerMappings賦值完成 3. 最後在DispatcherServlet#doDispatch()中,用對應的HandlerAdapter和Handler通過反射去請求controller中方法 #### 對requestMappingHandlerMapping進行initializeBean時register Handler 呼叫鏈: > AbstractApplicationContext#refresh() --> AbstractApplicationContext#finishBeanFactoryInitialization() --> DefaultListableBeanFactory#preInstantiateSingletons() --> AbstractBeanFactory#getBean() --> AbstractBeanFactory#doGetBean() --> AbstractAutowireCapableBeanFactory#createBean() --> AbstractAutowireCapableBeanFactory#doCreateBean() --> AbstractAutowireCapableBeanFactory#initializeBean() --> AbstractAutowireCapableBeanFactory#invokeInitMethods() --> RequestMappingHandlerMapping#afterPropertiesSet() --> AbstractHandlerMethodMapping#afterPropertiesSet() --> AbstractHandlerMethodMapping#initHandlerMethods() --> AbstractHandlerMethodMapping#processCandidateBean --> AbstractHandlerMethodMapping#detectHandlerMethods() --> RequestMappingHandlerMapping#registerHandlerMethod() --> AbstractHandlerMethodMapping#registerHandlerMethod() 在AbstractHandlerMethodMapping#initHandlerMethods()中先獲取所有的beanName,再挑選出符合條件的進行處理 ``` protected void initHandlerMethods() { //獲取容器中所有beanName for (String beanName : getCandidateBeanNames()) { if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { processCandidateBean(beanName); } } handlerMethodsInitialized(getHandlerMethods()); } ``` 判斷是Handler的才繼續呼叫detectHandlerMethods方法 ``` protected void processCandidateBean(String beanName) { Class beanType = null; ...... if (beanType != null && isHandler(beanType)) { detectHandlerMethods(beanName); } } ``` 滿足handler的條件是(RequestMappingHandlerMapping#isHandler()):@Controller或@RequestMapping進行註解 ``` @Override protected boolean isHandler(Class beanType) { return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) || AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class)); } ``` 滿足條件的,進行註冊 RequestMappingHandlerMapping#registerHandlerMethod() ``` @Override protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { super.registerHandlerMethod(handler, method, mapping); updateConsumesCondition(mapping, method); } ``` AbstractHandlerMethodMapping#registerHandlerMethod() ``` protected void registerHandlerMethod(Object handler, Method method, T mapping) { this.mappingRegistry.register(mapping, handler, method); } ``` 完成註冊。AbstractHandlerMethodMapping#register() ``` public void register(T mapping, Object handler, Method method) { this.readWriteLock.writeLock().lock(); try { HandlerMethod handlerMethod = createHandlerMethod(handler, method); validateMethodMapping(handlerMethod, mapping)