1. 程式人生 > 程式設計 >Mybatis外掛擴充套件及與Spring整合原理分析

Mybatis外掛擴充套件及與Spring整合原理分析

前言

前面幾篇文章分析了Mybatis的核心原理,但模組較多,沒有一一分析,更多的需要讀者自己下來研究。不過Mybatis的外掛擴充套件機制還是非常重要的,像PageHelper就是一個擴充套件外掛,熟悉其擴充套件原理,才能更好的針對我們的業務作出更合適的擴充套件。另外,現在Mybatis都是和Spring/SpringBoot一起使用,那麼Mybatis又是如何與它們進行整合的呢?一切答案盡在本文之中。

正文

外掛擴充套件

1. Interceptor核心實現原理

熟悉Mybatis配置的都知道,在xml配置中我們可以配置如下節點:

<plugins>
  <plugin interceptor="org.apache.ibatis.builder.ExamplePlugin">
   <property name="pluginProperty" value="100"/>
  </plugin>
 </plugins>

這個就是外掛的配置,那麼自然而然的這個節點就會在解析xml的時候進行解析,並將其新增到Configuration中。細心的讀者應該還記得下面這段程式碼,在XMLConfigBuilderl類中:

 private void parseConfiguration(XNode root) {
  try {
   //issue #117 read properties first
   //解析<properties>節點
   propertiesElement(root.evalNode("properties"));
   //解析<settings>節點
   Properties settings = settingsAsProperties(root.evalNode("settings"));
   loadCustomVfs(settings);
   //解析<typeAliases>節點
   typeAliasesElement(root.evalNode("typeAliases"));
   //解析<plugins>節點
   pluginElement(root.evalNode("plugins"));
   //解析<objectFactory>節點
   objectFactoryElement(root.evalNode("objectFactory"));
   //解析<objectWrapperFactory>節點
   objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
   //解析<reflectorFactory>節點
   reflectorFactoryElement(root.evalNode("reflectorFactory"));
   settingsElement(settings);//將settings填充到configuration
   // read it after objectFactory and objectWrapperFactory issue #631
   //解析<environments>節點
   environmentsElement(root.evalNode("environments"));
   //解析<databaseIdProvider>節點
   databaseIdProviderElement(root.evalNode("databaseIdProvider"));
   //解析<typeHandlers>節點
   typeHandlerElement(root.evalNode("typeHandlers"));
   //解析<mappers>節點
   mapperElement(root.evalNode("mappers"));
  } catch (Exception e) {
   throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e,e);
  }
 }

其中pluginElement就是解析外掛節點的:

private void pluginElement(XNode parent) throws Exception {
  if (parent != null) {
   //遍歷所有的外掛配置
   for (XNode child : parent.getChildren()) {
  	//獲取外掛的類名
    String interceptor = child.getStringAttribute("interceptor");
    //獲取外掛的配置
    Properties properties = child.getChildrenAsProperties();
    //例項化外掛物件
    Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
    //設定外掛屬性
    interceptorInstance.setProperties(properties);
    //將外掛新增到configuration物件,底層使用list儲存所有的外掛並記錄順序
    configuration.addInterceptor(interceptorInstance);
   }
  }
 }

從上面可以看到,就是根據配置例項化為Interceptor物件,並新增到InterceptorChain中,該類的物件被Configuration持有。Interceptor包含三個方法:

 //執行攔截邏輯的方法
 Object intercept(Invocation invocation) throws Throwable;

 //target是被攔截的物件,它的作用就是給被攔截的物件生成一個代理物件
 Object plugin(Object target);

 //讀取在plugin中設定的引數
 void setProperties(Properties properties);

而InterceptorChain只是儲存了所有的Interceptor,並提供方法給客戶端呼叫,使得所有的Interceptor生成代理物件:

public class InterceptorChain {

 private final List<Interceptor> interceptors = new ArrayList<>();

 public Object pluginAll(Object target) {
  for (Interceptor interceptor : interceptors) {
   target = interceptor.plugin(target);
  }
  return target;
 }

 public void addInterceptor(Interceptor interceptor) {
  interceptors.add(interceptor);
 }
 
 public List<Interceptor> getInterceptors() {
  return Collections.unmodifiableList(interceptors);
 }

}

可以看到pluginAll就是迴圈去呼叫了Interceptor的plugin方法,而該方法的實現一般是通過Plugin.wrap去生成代理物件:

public static Object wrap(Object target,Interceptor interceptor) {
	//解析Interceptor上@Intercepts註解得到的signature資訊
  Map<Class<?>,Set<Method>> signatureMap = getSignatureMap(interceptor);
  Class<?> type = target.getClass();//獲取目標物件的型別
  Class<?>[] interfaces = getAllInterfaces(type,signatureMap);//獲取目標物件實現的介面
  if (interfaces.length > 0) {
   //使用jdk的方式建立動態代理
   return Proxy.newProxyInstance(
     type.getClassLoader(),interfaces,new Plugin(target,interceptor,signatureMap));
  }
  return target;
 }

其中getSignatureMap就是將@Intercepts註解中的value值解析並快取起來,該註解的值是@Signature型別的陣列,而這個註解可以定義class型別、方法、引數,即攔截器的定位。而getAllInterfaces就是獲取要被代理的介面,然後通過JDK動態代理建立代理物件,可以看到InvocationHandler就是Plugin類,所以直接看invoke方法,最終就是呼叫interceptor.intercept方法:

 public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
  try {
   //獲取當前介面可以被攔截的方法
   Set<Method> methods = signatureMap.get(method.getDeclaringClass());
   if (methods != null && methods.contains(method)) {//如果當前方法需要被攔截,則呼叫interceptor.intercept方法進行攔截處理
    return interceptor.intercept(new Invocation(target,method,args));
   }
   //如果當前方法不需要被攔截,則呼叫物件自身的方法
   return method.invoke(target,args);
  } catch (Exception e) {
   throw ExceptionUtil.unwrapThrowable(e);
  }
 }

這裡的外掛實現思路是通用的,即這個interceptor我們可以用來擴充套件任何物件的任何方法,比如對Map的get進行攔截,可像下面這樣實現:

@Intercepts({
   @Signature(type = Map.class,method = "get",args = {Object.class})})
 public static class AlwaysMapPlugin implements Interceptor {
  @Override
  public Object intercept(Invocation invocation) throws Throwable {
   return "Always";
  }

  @Override
  public Object plugin(Object target) {
   return Plugin.wrap(target,this);
  }

  @Override
  public void setProperties(Properties properties) {
  }
 }

然後在使用Map時先用外掛對其包裝,這樣拿到的就是Map的代理物件。

 Map map = new HashMap();
  map = (Map) new AlwaysMapPlugin().plugin(map);

2. Mybatis的攔截增強

因為我們可以對Mybatis擴充套件任意多個的外掛,所以它使用InterceptorChain物件來儲存所有的外掛,這是責任鏈模式的實現。那麼Mybatis到底會攔截哪些物件和哪些方法呢?回憶上篇文章我們就可以發現Mybatis只會對以下4個物件進行攔截:

Executor:

 public Executor newExecutor(Transaction transaction,ExecutorType executorType) {
	......省略
	
  //通過interceptorChain遍歷所有的外掛為executor增強,新增外掛的功能
  executor = (Executor) interceptorChain.pluginAll(executor);
  return executor;
 }

StatementHandler

 public StatementHandler newStatementHandler(Executor executor,MappedStatement mappedStatement,Object parameterObject,RowBounds rowBounds,ResultHandler resultHandler,BoundSql boundSql) {
	//建立RoutingStatementHandler物件,實際由statmentType來指定真實的StatementHandler來實現
	StatementHandler statementHandler = new RoutingStatementHandler(executor,mappedStatement,parameterObject,rowBounds,resultHandler,boundSql);
  statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
  return statementHandler;
 }

ParameterHandler

 public ParameterHandler newParameterHandler(MappedStatement mappedStatement,BoundSql boundSql) {
  ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement,boundSql);
  parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
  return parameterHandler;
 }

ResultSetHandler

public ResultSetHandler newResultSetHandler(Executor executor,ParameterHandler parameterHandler,BoundSql boundSql) {
  ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor,parameterHandler,boundSql,rowBounds);
  resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
  return resultSetHandler;
 }

而具體要攔截哪些物件和哪些方法則是由@Intercepts和@Signature指定的。

以上就是Mybatis擴充套件外掛的實現機制,讀者可據此自行分析下PageHelper的實現原理。另外需要注意,我們在進行自定義外掛開發時,尤其要謹慎。因為直接關係到操作資料庫,如果對外掛的實現原理不透徹,很有可能引發難以估量的後果。

Mybatis與Spring整合原理

前面的示例都是單獨使用Mybatis,可以看到需要建立SqlSessionFactory和SqlSession物件,然後通過SqlSession去建立Mapper介面的代理物件,所以在與Spring整合時,顯而易見的,我們就需要考慮以下幾點:

  • 什麼時候建立以及怎麼建立SqlSessionFactory和SqlSession?
  • 什麼時候建立以及怎麼建立代理物件?
  • 如何將Mybatis的代理物件注入到IOC容器中?
  • Mybatis怎麼保證和Spring在同一個事務中並且使用的是同一個連線?

那麼如何實現以上幾點呢?下文基於mybatis-spring-1.3.3版本分析。

1. SqlSessionFactory的建立

熟悉Spring原始碼的(如果不熟悉,可以閱讀我之前的Spring系列原始碼)都知道Spring最重要的那些擴充套件點:

  • BeanDefinitionRegistryPostProcessor:Bean例項化前呼叫
  • BeanFactoryPostProcessor:Bean例項化前呼叫
  • InitializingBean:Bean例項化後呼叫
  • FactoryBean:實現該介面代替Spring管理一些特殊的Bean

其它還有很多,以上列舉出來的就是Mybatis整合Spring所用到的擴充套件點。首先我們需要例項化SqlSessionFactory,而例項化該物件在Mybatis裡實際上就是去解析一大堆配置並封裝到該物件中,所以我們不能簡單的使用<bean>標籤來配置,為此Mybatis實現了一個類SqlSessionFactoryBean(這個類我們在以前使用整合包時都會配置),之前XML中的配置都以屬性的方式放入到了該類中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="com.enjoylearning.mybatis.entity" />
		<property name="mapperLocations" value="classpath:sqlmapper/*.xml" />
	</bean>

進入這個類,我們可以看到它實現了InitializingBean和FactoryBean介面,實現第一個介面的作用就是在該類例項化後立即去執行配置解析的階段:

 public void afterPropertiesSet() throws Exception {
  notNull(dataSource,"Property 'dataSource' is required");
  notNull(sqlSessionFactoryBuilder,"Property 'sqlSessionFactoryBuilder' is required");
  state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),"Property 'configuration' and 'configLocation' can not specified with together");

  this.sqlSessionFactory = buildSqlSessionFactory();
 }

具體的解析就在buildSqlSessionFactory方法中,這個方法比較長,但不復雜,這裡就不貼程式碼了。而實現第二介面的作用就在於Spring獲取該類例項時實際上會通過getObject方法返回SqlSessionFactory的例項,通過這兩個介面就完成了SqlSessionFactory的例項化。

2. 掃描Mapper並建立代理物件

在整合之後我們除了要配置SqlSessionFactoryBean外,還要配置一個類:

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.enjoylearning.mybatis.mapper" />
	</bean>

這個類的作用就是用來掃描Mapper介面的,並且這個類實現了BeanDefinitionRegistryPostProcessor和InitializingBean,這裡實現第二個介面的作用主要是校驗有沒有配置待掃描包的路徑:

 public void afterPropertiesSet() throws Exception {
  notNull(this.basePackage,"Property 'basePackage' is required");
 }

主要看到postProcessBeanDefinitionRegistry方法:

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  if (this.processPropertyPlaceHolders) {
   processPropertyPlaceHolders();
  }

  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.registerFilters();
  scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage,ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
 }

這裡建立了一個掃描類,而這個掃描類是繼承自Spring的ClassPathBeanDefinitionScanner,也就是會將掃描到的類封裝為BeanDefinition註冊到IOC容器中去:

public int scan(String... basePackages) {
		int beanCountAtScanStart = this.registry.getBeanDefinitionCount();

		doScan(basePackages);

		// Register annotation config processors,if necessary.
		if (this.includeAnnotationConfig) {
			AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
		}

		return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
	}

 public Set<BeanDefinitionHolder> doScan(String... basePackages) {
  Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

  if (beanDefinitions.isEmpty()) {
   logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
  } else {
   processBeanDefinitions(beanDefinitions);
  }

  return beanDefinitions;
 }

 private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
  GenericBeanDefinition definition;
  for (BeanDefinitionHolder holder : beanDefinitions) {
   definition = (GenericBeanDefinition) holder.getBeanDefinition();

   if (logger.isDebugEnabled()) {
    logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() 
     + "' and '" + definition.getBeanClassName() + "' mapperInterface");
   }

   // the mapper interface is the original class of the bean
   // but,the actual class of the bean is MapperFactoryBean
   definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
   definition.setBeanClass(this.mapperFactoryBean.getClass());

   definition.getPropertyValues().add("addToConfig",this.addToConfig);

   boolean explicitFactoryUsed = false;
   if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
    definition.getPropertyValues().add("sqlSessionFactory",new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
    explicitFactoryUsed = true;
   } else if (this.sqlSessionFactory != null) {
    definition.getPropertyValues().add("sqlSessionFactory",this.sqlSessionFactory);
    explicitFactoryUsed = true;
   }

   if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
    if (explicitFactoryUsed) {
     logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
    }
    definition.getPropertyValues().add("sqlSessionTemplate",new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
    explicitFactoryUsed = true;
   } else if (this.sqlSessionTemplate != null) {
    if (explicitFactoryUsed) {
     logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
    }
    definition.getPropertyValues().add("sqlSessionTemplate",this.sqlSessionTemplate);
    explicitFactoryUsed = true;
   }

   if (!explicitFactoryUsed) {
    if (logger.isDebugEnabled()) {
     logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
    }
    definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
   }
  }
 }

你可能會好奇,在哪裡生成的代理物件?只是將Mapper介面注入到IOC有什麼用呢?其實關鍵程式碼就在definition.setBeanClass(this.mapperFactoryBean.getClass()),這句程式碼的作用就是將每一個Mapper介面都轉為MapperFactoryBean型別。
為什麼要這麼轉呢?進入這個類你會發現它也是實現了FactoryBean介面的,所以自然而然的又是利用它來建立代理實現類物件:

 public T getObject() throws Exception {
  return getSqlSession().getMapper(this.mapperInterface);
 }

3. 如何整合Spring事務

Mybatis作為一個ORM框架,它是有自己的資料來源和事務控制的,而Spring同樣也會配置這兩個,那麼怎麼將它們整合到一起呢?而不是在Service類呼叫Mapper介面時就切換了資料來源和連線,那樣肯定是不行的。
在使用Mybatis時,我們可以在xml中配置TransactionFactory事務工廠類,不過一般都會使用預設的JdbcTransactionFactory,而當與Spring整合後,預設的事務工廠類改為了SpringManagedTransactionFactory。回到SqlSessionFactoryBean讀取配置的方法,在該方法中有下面這樣一段程式碼:

if (this.transactionFactory == null) {
   this.transactionFactory = new SpringManagedTransactionFactory();
  }

	 configuration.setEnvironment(new Environment(this.environment,this.transactionFactory,this.dataSource));

上面預設建立了SpringManagedTransactionFactory,同時還將我們xml中ref屬性引用的dataSource新增到了Configuration中,這個工廠會建立下面這個事務控制物件:

public Transaction newTransaction(DataSource dataSource,TransactionIsolationLevel level,boolean autoCommit) {
  return new SpringManagedTransaction(dataSource);
 }

而這個方法是在DefaultSqlSessionFactory獲取SqlSession時會呼叫:

private SqlSession openSessionFromDataSource(ExecutorType execType,boolean autoCommit) {
  Transaction tx = null;
  try {
   final Environment environment = configuration.getEnvironment();
   final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
   tx = transactionFactory.newTransaction(environment.getDataSource(),level,autoCommit);
   final Executor executor = configuration.newExecutor(tx,execType);
   return new DefaultSqlSession(configuration,executor,autoCommit);
  } catch (Exception e) {
   closeTransaction(tx); // may have fetched a connection so lets call close()
   throw ExceptionFactory.wrapException("Error opening session. Cause: " + e,e);
  } finally {
   ErrorContext.instance().reset();
  }
 }

這就保證使用的是同一個資料來源物件,但是怎麼保證拿到的是同一個連線和事務呢?關鍵就在於SpringManagedTransaction獲取連線是怎麼實現的:

 public Connection getConnection() throws SQLException {
  if (this.connection == null) {
   openConnection();
  }
  return this.connection;
 }

 private void openConnection() throws SQLException {
  this.connection = DataSourceUtils.getConnection(this.dataSource);
  this.autoCommit = this.connection.getAutoCommit();
  this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection,this.dataSource);

  if (LOGGER.isDebugEnabled()) {
   LOGGER.debug(
     "JDBC Connection ["
       + this.connection
       + "] will"
       + (this.isConnectionTransactional ? " " : " not ")
       + "be managed by Spring");
  }
 }

這裡委託給了DataSourceUtils獲取連線:

public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
		try {
			return doGetConnection(dataSource);
		}
		catch (SQLException ex) {
			throw new CannotGetJdbcConnectionException("Could not get JDBC Connection",ex);
		}
	}

	public static Connection doGetConnection(DataSource dataSource) throws SQLException {
		Assert.notNull(dataSource,"No DataSource specified");

		ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
		if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
			conHolder.requested();
			if (!conHolder.hasConnection()) {
				logger.debug("Fetching resumed JDBC Connection from DataSource");
				conHolder.setConnection(dataSource.getConnection());
			}
			return conHolder.getConnection();
		}
		// Else we either got no holder or an empty thread-bound holder here.

		logger.debug("Fetching JDBC Connection from DataSource");
		Connection con = dataSource.getConnection();

		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			logger.debug("Registering transaction synchronization for JDBC Connection");
			// Use same Connection for further JDBC actions within the transaction.
			// Thread-bound object will get removed by synchronization at transaction completion.
			ConnectionHolder holderToUse = conHolder;
			if (holderToUse == null) {
				holderToUse = new ConnectionHolder(con);
			}
			else {
				holderToUse.setConnection(con);
			}
			holderToUse.requested();
			TransactionSynchronizationManager.registerSynchronization(
					new ConnectionSynchronization(holderToUse,dataSource));
			holderToUse.setSynchronizedWithTransaction(true);
			if (holderToUse != conHolder) {
				TransactionSynchronizationManager.bindResource(dataSource,holderToUse);
			}
		}

		return con;
	}

看到ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource)這段程式碼相信熟悉Spring原始碼的已經知道了,這個我在分析Spring事務原始碼時也講過,通過DataSource物件拿到當前執行緒繫結的ConnectionHolder,這個物件是在Spring開啟事務的時候存進去的。至此,關於Spring和Mybatis的整合原理我們就個搞清楚了,至於和SpringBoot的整合,讀者可自行分析。最後,我再分享一個小擴充套件知識。

4. FactoryBean的擴充套件知識

很多讀者可能不知道這個介面有什麼作用,其實很簡單,當我們有某個類由Spring例項化比較複雜,想要自己控制它的例項化時,就可以實現該介面。而實現該介面的類首先會被例項化並放入一級快取,而當我們依賴注入我們真正想要的類時(如Mapper介面的代理類),就會從一級快取中拿到FactoryBean實現類的例項,並判斷是否實現了FactoryBean介面,如果是就會呼叫getObject方法返回我們真正想要的例項。
那如果我們確實想要拿到的就是FactoryBean實現類的例項該怎麼辦呢?只需要在傳入的beanName前面加上“&”符號即可。

總結

本篇分析了Mybatis如何擴充套件外掛以及外掛的實現原理,但如非必要,切忌擴充套件外掛,如果一定要,那麼一定要非常謹慎。另外還結合Spirng的擴充套件點分析了Mybatis和Spring的整合原理,解決了困在我心中已久的一些疑惑,相信那也是大多數讀者的疑惑,好好領悟這部分內容非常有利於我們自己對Spring進行擴充套件。