舒適提示:本文基於Mybatis.3.x版本。java
MapperScannerConfigurer,Spring整合Mybatis的核心類,其做用是掃描項目中Dao類,將其建立爲Mybatis的Maper對象即MapperProxy對象。spring
首先進入源碼學習以前,咱們先看一下在項目中的配置文件信息。 sql
咱們注意到這裏有兩三個與Mapper相關的配置:apache
本文的行文思路以下:session
下面的源碼分析或許會比較枯燥,進入源碼分析以前,先給出MapperProxy的建立序列圖。併發
MapperScannerConfigurer的類圖以下所示: app
MapperScannerConfigurer實現Spring Bean生命週期相關的類:BeanNameAware、ApplicationContextAware、BeanFactoryPostProcessor、InitializingBean、BeanDefinitionRegistryPostProcessor,咱們先來看一下這些接口對應的方法的調用時機:源碼分析
那咱們接下來從BeanDefinitionRegistryPostProcessor的實現接口開始跟蹤。post
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { 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); // [@1](https://my.oschina.net/u/1198) 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)); // @2 }
代碼@1:首先設置SqlSessionFactory,從該Scan器生成的Mapper最終都是受該SqlSessionFactory的管轄。 代碼@2:調用ClassPathMapperScanner的scan方法進行掃描動做,接下來詳細介紹。學習
public Set<beandefinitionholder> doScan(String... basePackages) { Set<beandefinitionholder> beanDefinitions = super.doScan(basePackages); //[@1](https://my.oschina.net/u/1198) if (beanDefinitions.isEmpty()) { logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { processBeanDefinitions(beanDefinitions); // @2 } return beanDefinitions; }
代碼@1:首先調用父類(org.springframework.context.annotation.ClassPathBeanDefinitionScanner)方法,根據掃描的文件,構建對應的BeanDefinitionHolder對象。 代碼@2:對這些BeanDefinitions進行處理,對Bean進行加工,加入Mybatis特性。
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.getPropertyValues().add("mapperInterface", definition.getBeanClassName()); definition.setBeanClass(this.mapperFactoryBean.getClass()); // @1 definition.getPropertyValues().add("addToConfig", this.addToConfig); boolean explicitFactoryUsed = false; if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) { // @2 start definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName)); explicitFactoryUsed = true; } else if (this.sqlSessionFactory != null) { definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory); explicitFactoryUsed = true; } // @2 end if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) { // @3 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); } } }
該方法有3個關鍵點: 代碼@1:BeanDefinition中的beanClass設置的類爲MapperFactoryBean,即該BeanDefinition初始化的實例爲MapperFactoryBean,其名字能夠看出,這是一個FactoryBean對象,會經過其getObject方法進行構建具體實例。
代碼@2:將爲MapperFactoryBean設置屬性,將SqlSessionFactory放入其屬性中,在實例化時能夠自動獲取到該SqlSessionFactory。
代碼@3:若是sqlSessionTemplate不爲空,則放入到屬性中,以便Spring在實例化MapperFactoryBean時能夠獲得對應的SqlSessionTemplate。
分析到這裏,MapperScannerConfigurer的doScan方法就結束了,但並無初始化Mapper,只是建立了不少的BeanDefinition,而且其beanClass爲MapperFactoryBean,那咱們將目光轉向MapperFactoryBean。
MapperFactoryBean的類圖以下:
先對上述核心類作一個簡述:
Dao層的基類,定義一個模板方法,供其子類實現具體的邏輯,DaoSupport的模板方法以下:
public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { // Let abstract subclasses check their configuration. checkDaoConfig(); // @1 // Let concrete implementations initialize themselves. try { initDao(); // @2 } catch (Exception ex) { throw new BeanInitializationException("Initialization of DAO failed", ex); } }
代碼@1:檢查或構建dao的配置信息,該方法爲抽象類,供子類實現,等下咱們本節的主角MapperFactoryBean主要實現該方法,從而實現與Mybatis相關的整合信息。 代碼@2:初始化Dao相關的方法,該方法爲一個空實現。
SqlSession支持父類,經過使用SqlSessionFactory或SqlSessionTemplate建立SqlSession,那下面兩個方法會在何時被調用呢?
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate)
不知道你們還記不記得,在建立MapperFactoryBean的時候,其屬性裏會設置SqlSessionFacotry或SqlSessionTemplate,見上文代碼(processBeanDefinitions),這樣的話在示例化Bean時,Spring會自動注入實例,即在實例化Bean時,上述方法中的一個或多個會被調用。
主要看它是如何實現checkDaoConfig的。
MapperFactoryBean#checkDaoConfig protected void checkDaoConfig() { super.checkDaoConfig(); // @1 notNull(this.mapperInterface, "Property 'mapperInterface' is required"); Configuration configuration = getSqlSession().getConfiguration(); if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) { // @2 try { configuration.addMapper(this.mapperInterface); } catch (Throwable t) { logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", t); throw new IllegalArgumentException(t); } finally { ErrorContext.instance().reset(); } } }
代碼@1:首先先調用父類的checkDaoConfig方法。
接下來進入到org.apache.ibatis.session.Configuration中。
public <t> void addMapper(Class<t> type) { mapperRegistry.addMapper(type); } public <t> T getMapper(Class<t> type, SqlSession sqlSession) { return mapperRegistry.getMapper(type, sqlSession); } public boolean hasMapper(Class<!--?--> type) { return mapperRegistry.hasMapper(type); }
從上面代碼能夠看出,正在註冊(添加)、查詢、獲取Mapper的核心類爲MapperRegistry。
其核心類圖以下所示:
對其屬性作個簡單的介紹:
下面簡單介紹MapperRegistry的幾個方法,其實現都比較簡單。
public <t> void addMapper(Class<t> type) { if (type.isInterface()) { if (hasMapper(type)) { // @1 throw new BindingException("Type " + type + " is already known to the MapperRegistry."); } boolean loadCompleted = false; try { knownMappers.put(type, new MapperProxyFactory<t>(type)); // @2 MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); // @3 parser.parse(); loadCompleted = true; } finally { if (!loadCompleted) { knownMappers.remove(type); } } } }
代碼@1:若是該接口已經註冊,則拋出已經綁定的異常。 代碼@2:爲該接口註冊MapperProxyFactory,但這裏只是註冊其建立MapperProxy的工廠,並非建立MapperProxy。 代碼@3:若是Mapper對應的xml資源未加載,觸發xml的綁定操做,將xml中的sql語句與Mapper創建關係。本文將不詳細介紹,在下一篇中詳細介紹。
注意:addMapper方法,只是爲*Mapper建立對應對應的MapperProxyFactory。
public <t> T getMapper(Class<t> type, SqlSession sqlSession) { final MapperProxyFactory<t> mapperProxyFactory = (MapperProxyFactory<t>) knownMappers.get(type); // @1 if (mapperProxyFactory == null) throw new BindingException("Type " + type + " is not known to the MapperRegistry."); try { return mapperProxyFactory.newInstance(sqlSession); // @2 } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
根據Mapper接口與SqlSession建立MapperProxy對象。 代碼@1:根據接口獲取MapperProxyFactory。 代碼@2:調用MapperProxyFactory的newInstance建立MapperProxy對象。
到目前爲止Mybatis Mapper的初始化構造過程就完成一半了,即MapperScannerConfigurer經過包掃描,而後構建MapperProxy,但此時MapperProxy還未與mapper.xml文件中的sql語句創建關聯,因爲篇幅的緣由,將在下一節重點介紹其關聯關係創建的流程。接下來咱們先一睹MapperProxy對象,畢竟這是本文最終要建立的對象,也爲後續SQL的執行流程作個簡單準備。
類圖以下:
上面的類都比較簡單,MapperMethod,表明一個一個的Mapper方法,從SqlCommand能夠看出,每個MapperMethod都會對應一條SQL語句。
下面以一張以SqlSessionFacotry爲視角的各核心類的關係圖:
舒適提示:本文只闡述了Mybatis MapperProxy的建立流程,MapperProxy與*.Mapper.xml即SQL是如何關聯的本文未涉及到,這部分的內容請看下文,即將發佈。
做者介紹: 丁威,《RocketMQ技術內幕》做者,RocketMQ 社區佈道師,公衆號:中間件興趣圈 維護者,目前已陸續發表源碼分析Java集合、Java 併發包(JUC)、Netty、Mycat、Dubbo、RocketMQ、Mybatis等源碼專欄。