DispatcherServlet在啟動時會根據配置文件創建HandlerMapping,這些HandlerMapping都實現了Ordered接口,DispatcherServlet實例化所有的HandlerMapping后放到一個集合中,並根據order對HandlerMapping進行排序。
DispatcherServlet在接受請求時會循環遍歷有序的HandlerMapping集合,RequestMappingHandlerMapping的order是0,開始接收請求。
RequestMappingHandlerMappin繼承AbstractHandlerMethodMapping,AbstractHandlerMethodMapping實現了InitializingBean,在實例化后對調用afterPropertiesSet方法,該方法完成method handler的注冊:
- public void afterPropertiesSet() {
- initHandlerMethods();
- }
- /**
- * Scan beans in the ApplicationContext, detect and register handler methods.
- * @see #isHandler(Class)
- * @see #getMappingForMethod(Method, Class)
- * @see #handlerMethodsInitialized(Map)
- */
- protected void initHandlerMethods() {
- if (logger.isDebugEnabled()) {
- logger.debug("Looking for request mappings in application context: " + getApplicationContext());
- }
- String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
- BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
- getApplicationContext().getBeanNamesForType(Object.class));
- for (String beanName : beanNames) {
- if (isHandler(getApplicationContext().getType(beanName))){
- detectHandlerMethods(beanName);
- }
- }
- handlerMethodsInitialized(getHandlerMethods());
- }