RequestMappingHandlerAdapter请求映射处理适配器,在SpringMVC中它是一个非常重要的类,对请求处理方法的调用主要是通过这个类来完成的(这段代码mv = ha.handle(processedRequest, response, mappedHandler.getHandler());)。下面我们就简单的分析一下这个类。首先我们先看一下它的UML类图结构:
画红线的部分是需要我们注意的一些类,如果你对Spring的Bean生命在周期熟悉的话,你会发现这些都是Spring的Bean生命周期相关的一些类(Spring Bean的生命周期小析(一)和Spring Bean的生命周期小析(二))。我们分析RequestMappingHandlerAdapter的时候也会从这些接口的实现方法中开始。首先我们先看一下它的构造函数:
public RequestMappingHandlerAdapter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
this.messageConverters = new ArrayList>(4);
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(stringHttpMessageConverter);
this.messageConverters.add(new SourceHttpMessageConverter
从上面的代码中我们可以看到这里默认添加了四种类型的Http数据转换器。其中我们需要关注的时候AllEncompassingFormHttpMessageConverter这个转换器,我们也去它的构造函数中看一下:
public AllEncompassingFormHttpMessageConverter() {
addPartConverter(new SourceHttpMessageConverter
其实在它的父类中还添加了三种类型的Convert:
public FormHttpMessageConverter() {
//application/x-www-form-urlencoded
this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
//multipart/form-data
this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);
//ByteArrayHttpMessageConverter
this.partConverters.add(new ByteArrayHttpMessageConverter());
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false);
//StringHttpMessageConverter
this.partConverters.add(stringHttpMessageConverter);
//ResourceHttpMessageConverter
this.partConverters.add(new ResourceHttpMessageConverter());
applyDefaultCharset();
}
按照Spring的Bean的生命周期的执行顺序,这里会先调用BeanFactoryAware#setBeanFactory方法、接着调用ApplicationContextAware#setApplicationContext方法,最后调用InitializingBean#afterPropertiesSet方法。我们先看一下重写之后的setBeanFactory方法的源码:
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ConfigurableBeanFactory) {
this.beanFactory = (ConfigurableBeanFactory) beanFactory;
}
}
这个方法的内容很简单,就是设置一下beanFactory的属性值(其实这里的beanFactory是DefaultListableBeanFactory的实例)。
public final void setApplicationContext(ApplicationContext context) throws BeansException {
//isContextRequired()方法返回true
if (context == null && !isContextRequired()) {
// Reset internal context state.
this.applicationContext = null;
this.messageSourceAccessor = null;
}
else if (this.applicationContext == null) {
// Initialize with passed-in context.
//所传入的context如果不能被实例化,则抛出异常
if (!requiredContextClass().isInstance(context)) {
throw new ApplicationContextException(
"Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]");
}
this.applicationContext = context;
//国际化
this.messageSourceAccessor = new MessageSourceAccessor(context);
//初始化ApplicationContext
initApplicationContext(context);
}
else {
// Ignore reinitialization if same context passed in.
if (this.applicationContext != context) {
throw new ApplicationContextException(
"Cannot reinitialize with different application context: current one is [" +
this.applicationContext + "], passed-in one is [" + context + "]");
}
}
}
我们主要看一下WebApplicationObjectSupport#initApplicationContext这个方法的内容:
@Override
protected void initApplicationContext(ApplicationContext context) {
//调用父类中的initApplicationContext方法
super.initApplicationContext(context);
if (this.servletContext == null && context instanceof WebApplicationContext) {
this.servletContext = ((WebApplicationContext) context).getServletContext();
if (this.servletContext != null) {
//初始化ServletContext
initServletContext(this.servletContext);
}
}
}
这里先调用父类中的initApplicationContext方法,然后会初始ServletContext。先看一下ApplicationObjectSupport#initApplicationContext方法:
protected void initApplicationContext(ApplicationContext context) throws BeansException {
initApplicationContext();
}
在我们的这个类的继承体系中,initApplicationContext();是一个空实现。同样initServletContext也是一个空实现。接下来我们要分析的一个重点InitializingBean#afterPropertiesSet的方法,它的源码内容如下,下面我们一点一点的分析这个类:
public void afterPropertiesSet() {
// Do this first, it may add ResponseBody advice beans
initControllerAdviceCache();
if (this.argumentResolvers == null) {
List resolvers = getDefaultArgumentResolvers();
this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
if (this.initBinderArgumentResolvers == null) {
List resolvers = getDefaultInitBinderArgumentResolvers();
this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
if (this.returnValueHandlers == null) {
List handlers = getDefaultReturnValueHandlers();
this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
}
}
我们先看initControllerAdviceCache这个方法:
private void initControllerAdviceCache() {
//通过上面的分析我们知道,这个方法的内容不为null
if (getApplicationContext() == null) {
return;
}
//获取所有带ControllerAdvice注解的类
List beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
//对获取到的ControllerAdvice注解的类进行排序,排序的规则是基于实现PriorityOrdered接口或者带有Order注解
AnnotationAwareOrderComparator.sort(beans);
List
在这个方法里主要是获取了带ControllerAdvice注解的类,并从这些类中查找实现了RequestBodyAdvice或者ResponseBodyAdvice接口的类,添加到requestResponseBodyAdvice集合中,另外获取所有带ModelAttribute注解且没有RequestMapping注解的方法,放到modelAttributeAdviceCache集合中,获取所有带InitBinder注解的方法放到initBinderAdviceCache的集合中。下面我们再看这一段代码:
if (this.argumentResolvers == null) {
List resolvers = getDefaultArgumentResolvers();
this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
private HandlerMethodArgumentResolverComposite argumentResolvers;
argumentResolvers这个属性是HandlerMethodArgumentResolverComposite 类型的,如果我们在配置RequestMappingHandlerAdapter的时候设置了一系列HandlerMethodArgumentResolver的实现类的话,如下所示,
public void setArgumentResolvers(List argumentResolvers) {
if (argumentResolvers == null) {
this.argumentResolvers = null;
}
else {
this.argumentResolvers = new HandlerMethodArgumentResolverComposite();
this.argumentResolvers.addResolvers(argumentResolvers);
}
}
它会先创建HandlerMethodArgumentResolverComposite对象,然后把配置的HandlerMethodArgumentResolver的实现类添加到HandlerMethodArgumentResolverComposite的对象中。这里我们是没有手工配置RequestMappingHandlerAdapter的,所以,会先调用getDefaultArgumentResolvers方法,获取一系列默认的HandlerMethodArgumentResolver的实现类,代码如下:
private List getDefaultArgumentResolvers() {
List resolvers = new ArrayList();
// 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(), this.requestResponseBodyAdvice));
resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));
resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
resolvers.add(new RequestHeaderMapMethodArgumentResolver());
resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new SessionAttributeMethodArgumentResolver());
resolvers.add(new RequestAttributeMethodArgumentResolver());
// Type-based argument resolution
resolvers.add(new ServletRequestMethodArgumentResolver());
resolvers.add(new ServletResponseMethodArgumentResolver());
resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
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;
}
SpringMVC为我们自动添加了大概26个HandlerMethodArgumentResolver的实现类。这里有一个方法需要我们注意一下:getCustomArgumentResolvers() 方法。这个方法是用来获取自定义的HandlerMethodArgumentResolver的实现类,也就是说如果我们有自己写的HandlerMethodArgumentResolver的方法的话,我们配置的属性是customArgumentResolvers,最好不要配置argumentResolvers这个属性。然后我们注意的一点是我们所添加的所以的HandlerMethodArgumentResolver的实现类,都是添加到了HandlerMethodArgumentResolverComposite这个类中,HandlerMethodArgumentResolverComposite也是HandlerMethodArgumentResolver的一个实现类。还有一点需要注意的是,这里创建了两个RequestParamMethodArgumentResolver的实例,一个传了true参数,一个传了false参数,这是用来解析不同的请求参数的,详情请看这里: SpringMVC之分析请求对应处理器方法参数的解析过程(一)