首先我们来看下AbstractHandlerMethodMapping这个类,它实现了InitializingBean接口,里面有个afterPropertiesSet()方法。这个接口是spring-beans这个组件的内容,想一想,平时使用搭建SpringMVC的时候,是不是把这个jar包也扔到项目里头了?对于spring-beans这个组件在这里就 不拓展了,我们只要知道实现了InitializingBean这个接口后,spring容器在对象实例化完后进行调用afterPropertiesSet()方法即可(注意这里是spring容器,而不是tomcat容器)。部分源码如下
public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean {
@Override
public void afterPropertiesSet() {
initHandlerMethods();
}
/**
* Scan beans in the ApplicationContext, detect and register handler methods.
*/
protected void initHandlerMethods() {
if (logger.isDebugEnabled()) {
logger.debug("Looking for request mappings in application context: " + getApplicationContext());
}
//取得容器的所有bean
String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
for (String beanName : beanNames) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
Class<?> beanType = null;
try {
beanType = getApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
}
}
//isHandler()方法用于提取有@Controller或者@RequestMapping的类
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());//此处SpringMVC并未做任何实现
}
protected void detectHandlerMethods(final Object handler) {
Class<