AbstractHandlerMethodMapping类详解 - HandlerMapping系列八
AbstractHandlerMethodMapping当bean被注入到容器后会执行一系列的初始化过程,用于注解@Controller,@RequestMapping来定义controller。
AbstractHandlerMethodMapping源码
//抽象方法,并实现了initializingBean接口,其实主要的注册操作则是通过afterPropertiesSet()接口方法来调用的 public abstract class AbstractHandlerMethodMappingextends AbstractHandlerMapping implements InitializingBean{} //容器启动时会运行此方法,完成handlerMethod的注册操作 @Override public void afterPropertiesSet() { initHandlerMethods(); } //handlerMethod的注册操作 protected void initHandlerMethods() { if (logger.isDebugEnabled()) { logger.debug("Looking for request mappings in application context: " + getApplicationContext()); } //从springMVC容器中获取所有的beanName String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) : getApplicationContext().getBeanNamesForType(Object.class)); //注册从容器中获取的beanName for (String name : beanNames) { if (!name.startsWith(SCOPED_TARGET_NAME_PREFIX) && isHandler(getApplicationContext().getType(name))) { detectHandlerMethods(name); } } handlerMethodsInitialized(getHandlerMethods()); } //根据beanName进行一系列的注册,最终实现是在registerHandlerMethod protected void detectHandlerMethods(final Object handler) { //获取bean实例 Class handlerType = (handler instanceof String ? getApplicationContext().getType((String) handler) : handler.getClass()); // Avoid repeated calls to getMappingForMethod which would rebuild RequestMappingInfo instances final Mapmappings = new IdentityHashMap (); final Class userType = ClassUtils.getUserClass(handlerType); Setmethods = HandlerMethodSelector.selectMethods(userType, new MethodFilter() { @Override public boolean matches(Method method) { //创建RequestMappingInfo T mapping = getMappingForMethod(method, userType); if (mapping != null) { mappings.put(method, mapping); return true; } else { return false; } } }); for (Method method : methods) { registerHandlerMethod(handler, method, mappings.get(method)); } } //注册beanName和method及RequestMappingInfo之间的关系,RequestMappingInfo会保存url信息 @Deprecated protected void registerHandlerMethod(Object handler, Method method, T mapping) { this.mappingRegistry.register(mapping, handler, method); }
进行HandlerMethod的注册操作,简单来说就是从springMVC的容器中获取所有的beanName,注册url和实现方法HandlerMethod的对应关系。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。