Spring系列之Mybatis動態代理實現全過程?回答正確率不到1%


面試中,可能會問到Spring怎么綁定Mapper接口和SQL語句的。一般的答案是Spring會為Mapper生成一個代理類,調用的時候實際調用的是代理類的實現。但是如果被追問代理類實現的細節,很多同學會卡殼,今天借助2張圖來閱讀一下代碼如何實現的。

一、代理工廠類生成的過程

file

步驟1

在啟動類上加上注解MapperScan

@SpringBootApplication
@MapperScan(basePackages = "com.example.springdatasourcedruid.dal")
public class SpringDatasourceDruidApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringDatasourceDruidApplication.class, args);
	}
}

步驟2

/**
*指定mapper接口所在的包,然后包下面的所有接口在編譯之后都會生成相應的實現類
*這個注解引入了MapperScannerRegistrar類
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
public @interface MapperScan {
  //掃描的包路徑列表
  String[] basePackages() default {};
  //代理工廠類類型
  Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;
  //作用范圍,這里默認是單例
  String defaultScope() default AbstractBeanDefinition.SCOPE_DEFAULT;
}

步驟3、4

實現ImportBeanDefinitionRegistrar接口,目的是實現動態創建自定義的bean

public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

  //Spring 會回調該方法
  @Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    //獲取MapperScan注解設置的全部屬性信息
    AnnotationAttributes mapperScanAttrs = AnnotationAttributes
        .fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
    if (mapperScanAttrs != null) {
      //調用具體的實現 
      registerBeanDefinitions(importingClassMetadata, mapperScanAttrs, registry,
          generateBaseBeanName(importingClassMetadata, 0));
    }
  }
  //注冊一個 BeanDefinition  ,這里會構建並且向容器中注冊一個bd 也就是一個自定義的掃描器 MapperScannerConfigurer
  //mapperFactoryBeanClass的類型MapperFactoryBean
  void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs,
      BeanDefinitionRegistry registry, String beanName) {
    //構建一個 BeanDefinition 他的實例對象是 MapperScannerConfigurer
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
    builder.addPropertyValue("processPropertyPlaceHolders", true);


    Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
    if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
      builder.addPropertyValue("mapperFactoryBeanClass", mapperFactoryBeanClass);
    }

    registry.registerBeanDefinition(beanName, builder.getBeanDefinition());

  }
}

步驟5

將MapperScannerConfigurer注冊到beanFactory,MapperScannerConfigurer是為了解決MapperFactoryBean繁瑣而生的,有了MapperScannerConfigurer就不需要我們去為每個映射接口去聲明一個bean了。大大縮減了開發的效率

步驟6、7

回調postProcessBeanDefinitionRegistry方法,目的是初始化掃描器,並且回調掃描basePackages下的接口,獲取到所有符合條件的記錄

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    if (this.processPropertyPlaceHolders) {
      processPropertyPlaceHolders();
    }
    //初始化掃描器,可以掃描項目下的class文件轉換成BeanDefinition  
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    scanner.setAddToConfig(this.addToConfig);
    scanner.setAnnotationClass(this.annotationClass);
    scanner.setMarkerInterface(this.markerInterface);
    scanner.setSqlSessionFactory(this.sqlSessionFactory);
    scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
    scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
    scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
    scanner.setResourceLoader(this.applicationContext);
    scanner.setBeanNameGenerator(this.nameGenerator);
    scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
    if (StringUtils.hasText(lazyInitialization)) {
      scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
    }
    if (StringUtils.hasText(defaultScope)) {
      scanner.setDefaultScope(defaultScope);
    }
	//這一步是很重要的,他是注冊了一系列的過濾器,使得Spring在掃描到Mapper接口的時候不被過濾掉  
    scanner.registerFilters();
	//執行掃描  
    scanner.scan(
        StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }

步驟8、9

將Mapper接口的實現設置為MapperFactoryBean,並且注冊到容器中,后面其他類依賴注入首先獲取到的是MapperFactoryBean

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    AbstractBeanDefinition definition;
    BeanDefinitionRegistry registry = getRegistry();
    for (BeanDefinitionHolder holder : beanDefinitions) {
      definition = (AbstractBeanDefinition) holder.getBeanDefinition();

      String beanClassName = definition.getBeanClassName();
      
      definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
      //將對應的Mapper接口,設置為MapperFactoryBean
      definition.setBeanClass(this.mapperFactoryBeanClass);

      definition.getPropertyValues().add("addToConfig", this.addToConfig);
      //-------忽略了非關鍵代碼--------------------------------
      //將Mapper接口注冊到BeanDefinition,這時候實際的實現類已經被指定為MapperFactoryBean
      registry.registerBeanDefinition(proxyHolder.getBeanName(), proxyHolder.getBeanDefinition());
      }

}

二、代理類的生成以及使用

我們根據上面的情況已經知道,實際在容器中保存的是MapperFactoryBean,這里也並不沒有和SQL關聯上,實際在依賴注入的時候,還會進行加工,獲取到真正的代理類,在下面的圖中進一步解釋。
file

步驟1

在xxxService用注解@Autowired(@Resource)、構造方法方式引入xxxMapper屬性

步驟2

通過調用AbstractBeanFactory.getBean方法獲取bean,此為方法入口

public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return this.doGetBean(name, requiredType, (Object[])null, false);
}

步驟3

因為容器中存在是MapperFactoryBean,所以后續是調用MapperFactoryBean.getObject方法,SqlSessionDaoSupport類中getSqlSession實際返回的是sqlSessionTemplate

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
	@Override
	public T getObject() throws Exception {
		return getSqlSession().getMapper(this.mapperInterface);
	}
}

步驟4

調用sqlSessionTemplate.getMapper,getConfiguration()獲取到的對象就是Configuration

@Override
public <T> T getMapper(Class<T> type) {
	return getConfiguration().getMapper(type, this);
}

步驟5

調用Configuration.getMapper方法

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
		return this.mapperRegistry.getMapper(type, sqlSession);
}

步驟6

調用MapperRegistry.getMapper方法,這里先從緩存中獲取MapperProxyFactory,然后再生成相應的實例

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
		MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
		if (mapperProxyFactory == null) {
				throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
		} else {
				try {
						return mapperProxyFactory.newInstance(sqlSession);
				} catch (Exception var5) {
						throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
				}
		}
}

步驟7、8

調用java動態代理類生成代理對象MapperProxy,並且返回

    protected T newInstance(MapperProxy<T> mapperProxy) {
        return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }
    
    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
        return this.newInstance(mapperProxy);
    }

步驟9

將xxxMapper設置到xxxService完成屬性注入

三、使用Mapper的過程

比如說我們要調用xxxMapper.insert方法

步驟1

上面講到我們實際注入的是動態代理對象MapperProxy,因此實際調用的是MapperProxy.invoke方法,依據代碼我們很容易得出后續走的方法是cachedInvoker.invoke,proxy即使MapperProxy對象,method即insert方法,args即為傳入要插入的實體對象

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		try {
				return Object.class.equals(method.getDeclaringClass()) ? method.invoke(this, args) : this.cachedInvoker(method).invoke(proxy, method, args, this.sqlSession);
		} catch (Throwable var5) {
				throw ExceptionUtil.unwrapThrowable(var5);
		}
}

因insert不是默認方法,因此執行的邏輯是 MapperProxy.PlainMethodInvoke

private MapperProxy.MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
        try {
            return (MapperProxy.MapperMethodInvoker)MapUtil.computeIfAbsent(this.methodCache, method, (m) -> {
                if (m.isDefault()) {
                    try {
                        return privateLookupInMethod == null ? new MapperProxy.DefaultMethodInvoker(this.getMethodHandleJava8(method)) : new MapperProxy.DefaultMethodInvoker(this.getMethodHandleJava9(method));
                    } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException var4) {
                        throw new RuntimeException(var4);
                    }
                } else {
								   //如果不是默認方法,執行該段邏輯
                    return new MapperProxy.PlainMethodInvoker(new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration()));
                }
            });
        } catch (RuntimeException var4) {
            Throwable cause = var4.getCause();
            throw (Throwable)(cause == null ? var4 : cause);
        }
    }

步驟2

執行PlainMethodInvoker.invoke方法

public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
		return this.mapperMethod.execute(sqlSession, args);
}

步驟3

這里才是真正和SQL相關的部分,方法的類型是根據xml文件中節點名稱獲取的,比如我們的例子中是insert,這里對應的就是case INSERT,后續的調用就是sqlSession和數據庫的關聯了

public Object execute(SqlSession sqlSession, Object[] args) {
		Object result;
		Object param;
		switch(this.command.getType()) {
		case INSERT:
				param = this.method.convertArgsToSqlCommandParam(args);
				result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));
				break;
		case UPDATE:
				param = this.method.convertArgsToSqlCommandParam(args);
				result = this.rowCountResult(sqlSession.update(this.command.getName(), param));
				break;
		case DELETE:
				param = this.method.convertArgsToSqlCommandParam(args);
				result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));
				break;
		case SELECT:
				if (this.method.returnsVoid() && this.method.hasResultHandler()) {
						this.executeWithResultHandler(sqlSession, args);
						result = null;
				} else if (this.method.returnsMany()) {
						result = this.executeForMany(sqlSession, args);
				} else if (this.method.returnsMap()) {
						result = this.executeForMap(sqlSession, args);
				} else if (this.method.returnsCursor()) {
						result = this.executeForCursor(sqlSession, args);
				} else {
						param = this.method.convertArgsToSqlCommandParam(args);
						result = sqlSession.selectOne(this.command.getName(), param);
						if (this.method.returnsOptional() && (result == null || !this.method.getReturnType().equals(result.getClass()))) {
								result = Optional.ofNullable(result);
						}
				}
				break;
		case FLUSH:
				result = sqlSession.flushStatements();
				break;
		default:
				throw new BindingException("Unknown execution method for: " + this.command.getName());
		}

		if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
				throw new BindingException("Mapper method '" + this.command.getName() + " attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
		} else {
				return result;
		}
}

四、總結

這里基本上從代理工廠類的生成、代理類的生成、以及使用的過程,結合上面兩幅圖和代碼,相信你已經有了充分的了解。
關注我,一起成長和進步,下一篇繼續
file


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM