AbstractDetectingUrlHandlerMapping类详解 - HandlerMapping系列三

AbstractDetectingUrlHandlerMapping是springMVC容器启动时扫描应用下的Object,迭代将url和handler的对应关系注册到handlerMap中。

initApplicationContext() 初始化容器

//初始化容器  
@Override  
public void initApplicationContext() throws ApplicationContextException {  
	super.initApplicationContext();  
	detectHandlers();  
}

AbstractDetectingUrlHandlerMapping也是通过重写initApplicationContext来注册Handler的,里面调用了detectHandlers方法,在detectHandlers中跟根据配置的detectHandlersInAncestorContexts参数从SpringMVC容器或者SpringMVC及其父类容器找到所有bean的beanName,然后用determineUrlsForHandler方法对每个beanName解析出对应的urls,如果解析结果不为空则将解析出的urls和beanName(作为Handler)注册到父类的Map,注册方法依然是调用AbstractUrlHandlerMapping的registerHandler方法。

detectHandlers() 注册每个bean对应的url的关系

protected void detectHandlers() throws BeansException {  
	if (logger.isDebugEnabled()) {  
		logger.debug("Looking for URL mappings in application context: " + getApplicationContext());  
	}  
	//获取容器的所有bean的名字  
	String[] beanNames = (this.detectHandlersInAncestorContexts ?  
			BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :  
			getApplicationContext().getBeanNamesForType(Object.class));  

	// Take any bean name that we can determine URLs for.  
	//对每个beanName解析url,如果能解析到就注册到父类的map中  
	for (String beanName : beanNames) {  
		//子类具体去实现  
		String[] urls = determineUrlsForHandler(beanName);  
		if (!ObjectUtils.isEmpty(urls)) {  
			// URL paths found: Let's consider it a handler.  
			//将解析的url注册到父类  
			registerHandler(urls, beanName);  
		}  
		else {  
			if (logger.isDebugEnabled()) {  
				logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");  
			}  
		}  
	}  
}
//抽象方法,子类中实现  
protected abstract String[] determineUrlsForHandler(String beanName); 

使用beanName解析urls的determineUrlsForHandler函数是在其子类中实现的,registerHandler函数操作是在父类AbstractUrlHandlerMapping中实现的,将bean和url的关系注册到handlerMap中。

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。