initHandlerMappings()方法初始化有两种方式:
1.setApplicationContext()
2.afterPropertiesSet()
1.setApplicationContext()实现方式如下:
首先进入DispatcherServlet 类中,可以看到DispatcherServlet 的继承关系:
DispatcherServlet extends FrameworkServlet
FrameworkServlet extends HttpServletBean implements ApplicationContextAware
ApplicationContextAware中只有:
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
此方法setApplicationContext实现类在 ApplicationObjectSupport中:
ApplicationObjectSupport implements ApplicationContextAware
public final void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
if (context == null && !isContextRequired()) {
// Reset internal context state.
this.applicationContext = null;
this.messageSourceAccessor = null;
}
else if (this.applicationContext == null) {
// Initialize with passed-in 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);
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 + "]");
}
}
}
//initApplicationContext(context);
protected void initApplicationContext(ApplicationContext context) throws BeansException {
initApplicationContext();
}
protected void initApplicationContext() throws BeansException {
}
initApplicationContext()方法由子类实现:
AbstractDetectingUrlHandlerMapping
SimpleUrlHandlerMapping
- AbstractDetectingUrlHandlerMapping实现:
public void initApplicationContext() throws ApplicationContextException {
//将匹配该映射器的Handler对象加入到this.HandlerMapping
super.initApplicationContext();
detectHandlers();
}
super.initApplicationContext();实现如下:
//super.initApplicationContext();实现在AbstractHandlerMapping类中:
//AbstractHandlerMapping extends WebApplicationObjectSupport implements HandlerMapping, Ordered
//拦截器一些设置
protected void initApplicationContext() throws BeansException {
extendInterceptors(this.interceptors);
//探测ApplicationContext中已经解析过的MappedInterceptor
detectMappedInterceptors(this.adaptedInterceptors);
//初始化拦截器
initInterceptors();
}
//initInterceptors();
protected void initInterceptors() {
if (!this.interceptors.isEmpty()) {
for (int i = 0; i < this.interceptors.size(); i++) {
Object interceptor = this.interceptors.get(i);
if (interceptor == null) {
throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");
}
this.adaptedInterceptors.add(adaptInterceptor(interceptor));
}
}
}
detectHandlers();实现如下:
protected void detectHandlers() throws BeansException {
ApplicationContext applicationContext = obt