HandlerAdapter初始化时,主要是进行注解解析器初始化注册;返回值处理类初始化;全局注解@ControllerAdvice内容读取并缓存.

目录:

  注解解析器初始化注册:@ModelAttribute(往model中添加属性)

  注解解析器初始化注册:@InitBinder(用于注册校验器,参数编辑器等)  

  返回值处理returnValueHandlers初始化

  全局的@ControllerAdvice注解使用类的@ModelAttribute 和 @InitBinder信息读取并缓存

注:具体解析器的分析还是看后续文章吧,要不文章跟裹脚布似的.

注解@ModelAttritue解析器初始化并注册

我们先看下@ModelAttribute注解的使用吧:

  1. 在注解中定义属性名,方法返回值

  2. 通过model直接设置

  3.  暂时没搞定

     // 在注解中定义属性名,方法返回值
@ModelAttribute("clazzName")
public String setModel() {
return this.getClass().getName();
}
// 通过model直接设置
@ModelAttribute
public void setModel1(Model model){
model.addAttribute("movie", "who");
}
// 暂时没搞定
@ModelAttribute()
public String setModel2(){
return "actor";
}

新建解析器时的逻辑:

  1 如果没有配置,直接读取默认实现

    这边默认实现多达24种+自定义实现,主要分为4类解析器:基于注解,基于类型,自定义,号称解析全部

  2 通过Composite封装,并注册

    解析策略实在太多,这边封装一个HandlerMethodArgumentResolverComposite,迭代解析器委托处理(有点责任链的味道)

先看初始化解析器,并注册的代码:

 package org.springframework.web.servlet.mvc.method.annotation;
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware,
InitializingBean {
public void afterPropertiesSet() {
if (this.argumentResolvers == null) {
List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
// ...
}
private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(); // Annotation-based argument resolution 基于注解的解析器
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
resolvers.add(new RequestParamMapMethodArgumentResolver());
resolvers.add(new PathVariableMethodArgumentResolver());
resolvers.add(new PathVariableMapMethodArgumentResolver());
resolvers.add(new MatrixVariableMethodArgumentResolver());
resolvers.add(new MatrixVariableMapMethodArgumentResolver());
resolvers.add(new ServletModelAttributeMethodProcessor(false));
resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters()));
resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters()));
resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
resolvers.add(new RequestHeaderMapMethodArgumentResolver());
resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); // Type-based argument resolution 基于类型的解析器
resolvers.add(new ServletRequestMethodArgumentResolver());
resolvers.add(new ServletResponseMethodArgumentResolver());
resolvers.add(new HttpEntityMethodProcessor(getMessageConverters()));
resolvers.add(new RedirectAttributesMethodArgumentResolver());
resolvers.add(new ModelMethodProcessor());
resolvers.add(new MapMethodProcessor());
resolvers.add(new ErrorsMethodArgumentResolver());
resolvers.add(new SessionStatusMethodArgumentResolver());
resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); // Custom arguments 自定义解析器
if (getCustomArgumentResolvers() != null) {
resolvers.addAll(getCustomArgumentResolvers());
} // Catch-all 全能的解析器
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
resolvers.add(new ServletModelAttributeMethodProcessor(true)); return resolvers;
}
}

然后是HandlerMethodArgumentResolverComposite迭代具体解析器委托处理的代码:

GOF对责任链意图的定义是:

  使多个对象都有机会iu处理请求,从而避免请求的发送者和接受者直接的耦合关系.将这些对象连成一条链,并沿这条链传递该请求,直到有一个对象处理它为止.

  从百度百科盗了个类图,来类比下:

上面是标准的责任链,下面是HandlerMethodReturnValueHandler部分类图

 package org.springframework.web.method.support;
public class HandlerMethodArgumentResolverComposite implements HandlerMethodArgumentResolver {
public Object resolveArgument(
MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
throws Exception { HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}
public boolean supportsParameter(MethodParameter parameter) {
return getArgumentResolver(parameter) != null;
}
private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
if (result == null) {
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
if (methodArgumentResolver.supportsParameter(parameter)) {
result = methodArgumentResolver;
this.argumentResolverCache.put(parameter, result);
break;
}
}
}
return result;
}
// ...
}

注解@InitBinder解析器初始化

先看@InitBinder注解的使用吧:

     /**
* 使用WebDataBinder实现日期校验
* @param dataBinder
*/
@InitBinder
public void dateFormat(WebDataBinder dataBinder){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,false));
}

这边的代码逻辑其实跟@ModelAttribute解析器初始化的逻辑是一样的,就不具体分析,只是这边初始化使用的解析器是不一样的.至于差异的原因,暂时还不知道,哪位有兴趣可以帮忙科普科普.

 package org.springframework.web.servlet.mvc.method.annotation;
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware,
InitializingBean {
private List<HandlerMethodArgumentResolver> getDefaultInitBinderArgumentResolvers() {
List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(); // Annotation-based argument resolution 基于注解的解析器
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
resolvers.add(new RequestParamMapMethodArgumentResolver());
resolvers.add(new PathVariableMethodArgumentResolver());
resolvers.add(new PathVariableMapMethodArgumentResolver());
resolvers.add(new MatrixVariableMethodArgumentResolver());
resolvers.add(new MatrixVariableMapMethodArgumentResolver());
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); // Type-based argument resolution 基于类型的解析器
resolvers.add(new ServletRequestMethodArgumentResolver());
resolvers.add(new ServletResponseMethodArgumentResolver()); // Custom arguments 自定义解析器
if (getCustomArgumentResolvers() != null) {
resolvers.addAll(getCustomArgumentResolvers());
} // Catch-all 全能的解析器
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true)); return resolvers;
}
// ...
}

返回值处理returnValueHandlers初始化

用于将handler处理器的返回值封装成ModelAndView.

这边的处理逻辑跟@ModelAttribute注解解析器的初始化高度雷同,我们还是看看使用的HandlerMethodReturnValueHandler接口

接口的定义方式也是高度雷同,一个api问是否支持,一个api进行具体处理.

 package org.springframework.web.method.support;
public interface HandlerMethodReturnValueHandler {
boolean supportsReturnType(MethodParameter returnType);
void handleReturnValue(Object returnValue,
MethodParameter returnType,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception; }

分类貌似也有一定的相似.

 package org.springframework.web.servlet.mvc.method.annotation;
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware,
InitializingBean {
private List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers() {
List<HandlerMethodReturnValueHandler> handlers = new ArrayList<HandlerMethodReturnValueHandler>(); // Single-purpose return value types 单一目的
handlers.add(new ModelAndViewMethodReturnValueHandler());
handlers.add(new ModelMethodProcessor());
handlers.add(new ViewMethodReturnValueHandler());
handlers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
handlers.add(new CallableMethodReturnValueHandler());
handlers.add(new DeferredResultMethodReturnValueHandler());
handlers.add(new AsyncTaskMethodReturnValueHandler(this.beanFactory)); // Annotation-based return value types 基于注解
handlers.add(new ModelAttributeMethodProcessor(false));
handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.contentNegotiationManager)); // Multi-purpose return value types 多目的
handlers.add(new ViewNameMethodReturnValueHandler());
handlers.add(new MapMethodProcessor()); // Custom return value types 自定义
if (getCustomReturnValueHandlers() != null) {
handlers.addAll(getCustomReturnValueHandlers());
} // Catch-all 又是全能
if (!CollectionUtils.isEmpty(getModelAndViewResolvers())) {
handlers.add(new ModelAndViewResolverMethodReturnValueHandler(getModelAndViewResolvers()));
}
else {
handlers.add(new ModelAttributeMethodProcessor(true));
} return handlers;
}
}

全局的@ControllerAdvice注解使用类的@ModelAttribute 和 @InitBinder信息读取并缓存

@ControllerAdvice注解主要是为了解决以下的场景问题:

  如果@ModelAttribute或@InitBinder注解如果需要在很多地方使用,怎么办?

  使用集成的话,由于java的单继承会限制父类,不够灵活.

使用时只需要如下添加注解就可以

 @ControllerAdvice()
public class AdviceController {
// ...
}

源码解析时,是通过InitializingBean的afterPropertiesSet调用initControllerAdviceCache初始化的解析器.

查找使用注解@ControllerAdivce的类时,通过spring迭代容器过滤容器中全部的类,找到使用ControllerAdvice.class的类并注册.

 package org.springframework.web.servlet.mvc.method.annotation;
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter implements BeanFactoryAware,
InitializingBean {
public void afterPropertiesSet() {
// ...
initControllerAdviceCache();
}
private void initControllerAdviceCache() {
// ...
// 扫描方式找到使用@ControllerAdvice的类
List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
Collections.sort(beans, new OrderComparator()); for (ControllerAdviceBean bean : beans) {
Set<Method> attrMethods = HandlerMethodSelector.selectMethods(bean.getBeanType(), MODEL_ATTRIBUTE_METHODS);
if (!attrMethods.isEmpty()) {
this.modelAttributeAdviceCache.put(bean, attrMethods);
}
Set<Method> binderMethods = HandlerMethodSelector.selectMethods(bean.getBeanType(), INIT_BINDER_METHODS);
if (!binderMethods.isEmpty()) {
this.initBinderAdviceCache.put(bean, binderMethods);
}
}
}
}

这边扫描获取类的方式跟之前的有所不同,我们可以细看下.

 1 package org.springframework.web.method;
2 public class ControllerAdviceBean implements Ordered {
3 /**
4 * Find the names of beans annotated with
5 * {@linkplain ControllerAdvice @ControllerAdvice} in the given
6 * ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
7 */
8 public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
9 List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
10 for (String name : applicationContext.getBeanDefinitionNames()) {
11 if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
12 beans.add(new ControllerAdviceBean(name, applicationContext));
13 }
14 }
15 return beans;
16 }
17 }

看下两个api在接口中定义:

  1. getBeanDefinitionNames 返回容器中定义的全部bean 的 name

  2. findAnnotationOnBean 查找类上定义的注解,包括父类与接口

 1 package org.springframework.beans.factory;
2 public interface ListableBeanFactory extends BeanFactory {
3 // ...
4 /**
5 * Return the names of all beans defined in this factory.
6 * <p>Does not consider any hierarchy this factory may participate in,
7 * and ignores any singleton beans that have been registered by
8 * other means than bean definitions.
9 * @return the names of all beans defined in this factory,
10 * or an empty array if none defined
11 */
12 String[] getBeanDefinitionNames();
13 /**
14 * Find a {@link Annotation} of {@code annotationType} on the specified
15 * bean, traversing its interfaces and super classes if no annotation can be
16 * found on the given class itself.
17 * @param beanName the name of the bean to look for annotations on
18 * @param annotationType the annotation class to look for
19 * @return the annotation of the given type found, or {@code null}
20 */
21 <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType);
22
23 }

顺便关心下@ControllerAdvice信息是如何保存的,就是对应的pojo ControllerAdviceBean:

这边只是记录bean,还没有添加添加根据类,包进行过滤匹配类的功能.

这边值得说的有3个:

  1. 根据类是否实现Ordered接口,设置排序顺序

  2. 扫描应用下使用ControllerAdvice注解的类就是上面说的api

  3. 实现getBeanType获取类的类型 和resolveBean获取类实例 ,这个算是advice的行为吧.作为容器的行为吧.

 1 package org.springframework.web.method;
2
3 public class ControllerAdviceBean implements Ordered {
4 // 使用注解的类
5 private final Object bean;
6 private final int order;
7 private final BeanFactory beanFactory;
8
9 public ControllerAdviceBean(String beanName, BeanFactory beanFactory) {
10 // ...
11 }
12
13 public ControllerAdviceBean(Object bean) {
14 // ...
15 }
16
17 // 如果类实现Ordered,根据order的值设置排序
18 private static int initOrderFromBeanType(Class<?> beanType) {
19 Order annot = AnnotationUtils.findAnnotation(beanType, Order.class);
20 return (annot != null) ? annot.value() : Ordered.LOWEST_PRECEDENCE;
21 }
22
23 private static int initOrderFromBean(Object bean) {
24 return (bean instanceof Ordered) ? ((Ordered) bean).getOrder() : initOrderFromBeanType(bean.getClass());
25 }
26
27 /**
28 * 扫描应用下使用ControllerAdvice注解的类
29 */
30 public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
31 List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
32 for (String name : applicationContext.getBeanDefinitionNames()) {
33 if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
34 beans.add(new ControllerAdviceBean(name, applicationContext));
35 }
36 }
37 return beans;
38 }
39
40 public Class<?> getBeanType() {
41 Class<?> clazz = (this.bean instanceof String)
42 ? this.beanFactory.getType((String) this.bean) : this.bean.getClass();
43
44 return ClassUtils.getUserClass(clazz);
45 }
46
47 public Object resolveBean() {
48 return (this.bean instanceof String) ? this.beanFactory.getBean((String) this.bean) : this.bean;
49 }
50 // ...
51 }

  

SpringMVC源码解析- HandlerAdapter初始化的更多相关文章

  1. SpringMVC源码解析- HandlerAdapter - ModelFactory(转)

    ModelFactory主要是两个职责: 1. 初始化model 2. 处理器执行后将modle中相应参数设置到SessionAttributes中 我们来看看具体的处理逻辑(直接充当分析目录): 1 ...

  2. SpringMVC源码解析- HandlerAdapter - ModelFactory

    ModelFactory主要是两个职责: 1. 初始化model 2. 处理器执行后将modle中相应参数设置到SessionAttributes中 我们来看看具体的处理逻辑(直接充当分析目录): 1 ...

  3. SpringMVC源码解析 - HandlerAdapter - @SessionAttributes注解处理

    使用SpringMVC开发时,可以使用@SessionAttributes注解缓存信息.这样业务开发时,就不需要一次次手动操作session保存,读数据. @Controller @RequestMa ...

  4. SpringMVC源码解析 - HandlerAdapter - HandlerMethodArgumentResolver

    HandlerMethodArgumentResolver主要负责执行handler前参数准备工作. 看个例子,红色部分的id初始化,填充值就是它干的活: @RequestMapping(value ...

  5. SpringMVC源码分析--容器初始化(五)DispatcherServlet

    上一篇博客SpringMVC源码分析--容器初始化(四)FrameworkServlet我们已经了解到了SpringMVC容器的初始化,SpringMVC对容器初始化后会进行一系列的其他属性的初始化操 ...

  6. SpringMVC源码分析--容器初始化(四)FrameworkServlet

    在上一篇博客SpringMVC源码分析--容器初始化(三)HttpServletBean我们介绍了HttpServletBean的init函数,其主要作用是初始化了一下SpringMVC配置文件的地址 ...

  7. springMVC源码解析--ViewResolver视图解析器执行(三)

    之前两篇博客springMVC源码分析--ViewResolver视图解析器(一)和springMVC源码解析--ViewResolverComposite视图解析器集合(二)中我们已经简单介绍了一些 ...

  8. SpringMVC源码分析--容器初始化(三)HttpServletBean

    在上一篇博客springMVC源码分析--容器初始化(二)DispatcherServlet中,我们队SpringMVC整体生命周期有一个简单的说明,并没有进行详细的源码分析,接下来我们会根据博客中提 ...

  9. springMVC源码分析--容器初始化(二)DispatcherServlet

    在上一篇博客springMVC源码分析--容器初始化(一)中我们介绍了spring web初始化IOC容器的过程,springMVC作为spring项目中的子项目,其可以和spring web容器很好 ...

随机推荐

  1. Spring Could与Dubbo、Docker、K8S

    如果你是在一个中小型项目中应用Spring Cloud,那么你不需要太多的改造和适配,就可以实现微服务的基本功能.但是如果是在大型项目中实践微服务,可能会发现需要处理的问题还是比较多,尤其是项目中老代 ...

  2. TongWEB与JOnAS 对比,国产中间件战斗机东方通TongWEB源码解析

    转自网址: http://bbs.51cto.com/thread-489819-1-1.html 首先需要声明的是,本人出于技术爱好的角度,以下的文字只是对所看到的一些情况的罗列,偶尔附加个人的一些 ...

  3. vmware克隆linux网络配置

    一.配置Linux网络 在安装Linux的时候,一定要保证你的物理网络的IP是手动设置的,要不然会在Linux设置IP连通网络的时候会报network is unreachable 并且怎么也找不到问 ...

  4. oracle数据库死锁的查看及解决

    Oracle常见死锁发生的原因以及解决方法 www.MyException.Cn  网友分享于:2014-09-02  浏览:0次       Oracle常见死锁发生的原因以及解决办法 一,删除和更 ...

  5. jython研究笔记

    jython目前只支持python2,不支持python3. python中使用第三方包的话需要重新设置lib的地址. public void getHtmlByTxt(String path) { ...

  6. 【转】httpservlet 文章

    HttpServlet类 ellisonDon 2012-10-25 12:42 阅读:2015 评论:0     HttpServlet的功能 ellisonDon 2012-10-25 11:02 ...

  7. 三大运营商2G/3G/4G频率分配和网络制式

    经过二十多年长期的发展,我国的通信业逐渐形成了2G/3G/4G并存的局面,手机通讯信号传输都是通过一定频率传输的,而三大运营商所拥有的频率和网络制式不尽相同,这就造成同一部手机在三大运营商之间可能不通 ...

  8. django2.0实现数据详情页展示的流程

    思路整理 1 先在urls.py中,定义路由获取的格式 url(r'^detail/(\d+)/$', views.blog_detail), 2 然后在views.py,定义数据获取的方法 def ...

  9. 很好用的log4j

  10. oracle 安装包

    Oracle Database 10g Release 2 (10.2.0.1.0) Enterprise/Standard Edition for Microsoft Windows (32-bit ...