HttpServlet
HttpServletBean
FrameworkServlet
DispatcherServlet
以上是DispatcherServlet的继承关系
初始化HandlerMapper的方法调用过程如下:
org.springframework.web.servlet.HttpServletBean.init()
org.springframework.web.servlet.HttpServletBean.initServletBean()
org.springframework.web.servlet.FrameworkServlet.initServletBean()
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext()
org.springframework.web.servlet.FrameworkServlet.onRefresh(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.onRefresh(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.initStrategies(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.initHandlerMappings(ApplicationContext)
初始化HandlerMapper函数:
/**
* Initialize the HandlerMappings used by this class.
* <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
* we default to BeanNameUrlHandlerMapping.
*/
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
//detectAllHandlerMappings 是否找出所有HandlerMapping
//如果不是,就只取名为“handlerMapping”的HandlerMapping
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
OrderComparator.sort(this.handlerMappings);
}
}
else {
try {
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}
//最后,确保有一个HandlerMapping,如果上面都找不到,就拿默认的
// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
}
}
}