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

程式設計師阿牛發表於2021-09-08

面試中,可能會問到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

相關文章