HandlerAdapter继承关系图:
DispatcherServlet#getHandlerAdapter()方法实现:
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isTraceEnabled()) {
logger.trace("Testing handler adapter [" + ha + "]");
}
//如果该适配器支持当前handler, 则直接返回该适配器
if (ha.supports(handler)) {
return ha;
}
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
分析: 遍历所有已注册的适配器, 调用适配器的supports()方法, 判断该适配器是否支持当前处理器, 如果支持, 则返回该适配器
HandlerAdapter接口中定义的方法:
public interface HandlerAdapter {
/**
* 查看当前适配器是否支持该处理器
*/
boolean supports(Object handler);
/**
* 处理请求
*/
@Nullable
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
long getLastModified(HttpServletRequest request, Object handler);
}
实现子类逻辑:
子类1: HttpRequestHandlerAdapter
public class HttpRequestHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
return (handler instanceof HttpRequestHandler);
}
@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
((HttpRequestHandler) handler).handleRequest(request, response);
return null;
}
@Override
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
}
}
子类2: SimpleControllerHandlerAdapter
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
return (handler instanceof Controller);
}
@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return ((Controller) handler).handleRequest(request, response);
}
@Override
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
}
}
子类3: SimpleServletHandlerAdapter
public class SimpleServletHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
return (handler instanceof Servlet);
}
@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
((Servlet) handler).service(request, response);
return null;
}
@Override
public long getLastModified(HttpServletRequest request, Object handler) {
return -1;
}
}
子类4: AbstractHandlerMethodAdapter
public abstract class AbstractHandlerMethodAdapter extends WebContentGenerator implements HandlerAdapter, Ordered {
. . . . . .
@Override
public final boolean supports(Object handler) {
return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
}
protected abstract boolean supportsInternal(HandlerMethod handlerMethod);
@Override
@Nullable
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/**
* Spring默认处理适配器为:RequestMappingHandlerAdapter(注解处理器适配器)
* {@link RequestMappingHandlerAdapter#handleInternal(HttpServletRequest,HttpServletResponse,HandlerMethod)}
*/
return handleInternal(request, response, (HandlerMethod) handler);
}
@Nullable
protected abstract ModelAndView handleInternal(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod) throws Exception;
@Override
public final long getLastModified(HttpServletRequest request, Object handler) {
return getLastModifiedInternal(request, (HandlerMethod) handler);
}
protected abstract long getLastModifiedInternal(HttpServletRequest request, HandlerMethod handlerMethod);
}
AbstractHandlerMethodAdapter子类相关方法逻辑实现:
RequestMappingHandlerAdapter的supportsInternal()方法实现:
@Override
protected boolean supportsInternal(HandlerMethod handlerMethod) {
return true;
}
RequestMappingHandlerAdapter的handleInternal()方法实现:
@Override
protected ModelAndView handleInternal(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
ModelAndView mav;
checkRequest(request);
// 如果需要,在同步块中执行invokeHandlerMethod。
if (this.synchronizeOnSession) {
HttpSession session = request.getSession(false);
if (session != null) {
Object mutex = WebUtils.getSessionMutex(session);
synchronized (mutex) {
mav = invokeHandlerMethod(request, response, handlerMethod);
}
}
else {
// No HttpSession available -> no mutex necessary
mav = invokeHandlerMethod(request, response, handlerMethod);
}
}
else {
//完全不需要会话同步。
/**
* {@link RequestMappingHandlerAdapter#invokeHandlerMethod(HttpServletRequest, HttpServletResponse, HandlerMethod)}
*/
mav = invokeHandlerMethod(request, response, handlerMethod);
}
if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
}
else {
prepareResponse(response);
}
}
return mav;
}
那么适配器是何时被加载到容器中的呢?
DispatcherServlet#initHandlerAdapters()方法实现:
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
//如果detectAllHandlerAdapters为true, 则开启探测所有处理适配器
if (this.detectAllHandlerAdapters) {
/**
* 在应用上下文中找到所有的处理适配器, 包括顶级上下文
*/
Map<String, HandlerAdapter> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerAdapters);
}
}
else {
try {
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
// 如果出现异常导致获取的适配器为空,则忽略, 后面将会设置默认的适配器
}
}
//如果没有获取到适配器, 则这里会注册默认的适配器
if (this.handlerAdapters == null) {
this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
if (logger.isDebugEnabled()) {
logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
}
}
}
BeanFactoryUtils#beansOfTypeIncludingAncestors()方法实现:
public static <T> Map<String, T> beansOfTypeIncludingAncestors(
ListableBeanFactory lbf, Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
Map<String, T> result = new LinkedHashMap<>(4);
result.putAll(lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit));
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
/**
* 进入递归, 从当前BeanFactory向上查询, 将探测到的Bean进行判断, 符合条件的加入result集合中
*/
Map<String, T> parentResult = beansOfTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
parentResult.forEach((beanName, beanType) -> {
if (!result.containsKey(beanName) && !hbf.containsLocalBean(beanName)) {
result.put(beanName, beanType);
}
});
}
}
return result;
}
查看DispatcherServlet#initHandlerAdapters()方法的调用栈:
分析:
- 模块1主要逻辑为创建以及配置Web应用上下文(WebApplicationContext)
- 模块2主要逻辑为springMVC相关bean对象注册解析, 即WebApplicationContext的实例化; 在结束初始化后, 发送结束事件, 由SimpleApplicationEventMulticaster激活监听器SourceFilteringListener的相关方法
- 模块3主要逻辑为触发DispatcherServlet的初始化方法, 开始初始化各种组件;
模块3逻辑分析:
在onRefresh()方法中调用DispatcherServlet的initStrategies()方法
DispatcherServlet#initStrategies()方法实现:
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
分析:
- 在initStrategies()方法中可以看到处理映射器, 适配器, 视图解析器, 异常解析器等后是在这里进行初始化, 这里适配器的初始化时通过initHandlerAdapters()方法实现, 在上面已经分析过, 这里不再赘述;
- initStrategies()方法的主要作用, 就是从Spring容器中获取到已经注册的各种Bean,也就是SpringMVC需要的各种组件对象, 获取到指定的组件实例后, 将其注册到SpringMVC的各种子容器中, 以便后面进行获取;[ ps: 这里可以深刻体会到Spring容器的强大!]
- Spring在解析 <mvc:annotation-driven /> 标签时会帮我们注入 RequestMappingHandlerAdapter 、HttpRequestHandlerAdapter 和 SimpleControllerHandlerAdapter 这三个适配器,需要注意下不要手动重复注入。当没有配置 <mvc:annotation-driven /> 标签时容器在初始化的时候检测到会自动注入 RequestMappingHandlerAdapter 、HttpRequestHandlerAdapter 和 SimpleControllerHandlerAdapter 这三个适配器
至此, 处理适配器解析完成;
相关文章:
SpringMVC源码解析一(在Spring源码项目中搭建SpringMVC源码模块)
SpringMVC源码解析三(处理映射器HandlerMapping的解析)
SpringMVC源码解析四(处理适配器HandlerAdapter的解析)
SpringMVC源码解析五(HandlerMethod执行过程解析)