Mybaits3源碼分析(二):掃描Mapper關聯到spring IOC容器,mybaits3ioc

來源:互聯網
上載者:User

Mybaits3源碼分析(二):掃描Mapper關聯到spring IOC容器,mybaits3ioc

    首先講講mapper是怎麼從配置到對象的。

<!-- 採用自動掃描方式建立mapper bean(單個更新模式) -->  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">      <property name="basePackage" value="com.xxx.dao" />      <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplateSimple" />      <property name="markerInterface" value="com.xxx.dao.SimpleDao" />  </bean>  

        實現了basePackage下所有實現了markerInterface指明的類的介面都會被掃描解析到。MapperScannerConfigurer實現了BeanDefinitionRegistryPostProcessor(BeanDefinitionRegistry後置處理器,想想Spring AOP)介面,使其能在Spring ApplicationContext容器註冊了所有BeanDefinition後調用它的postProcessBeanDefinitionRegistry方法。下面我們看看MapperScannerConfigurer是怎麼實現這個方法的。

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {    if (this.processPropertyPlaceHolders) {      //處理一些.properties中配置的mybaits有關的屬性,例如sqlSessionFactoryBeanName      processPropertyPlaceHolders();    }    //建立類路徑掃描器    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);    //根據配置為scanner定義掃描規則    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();    //開始掃描,參數中使用了tokenizeToStringArray函數來處理多basePackage的情況一般是“;”分隔    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));  }
     ClassPathMapperScanner類的父類ClassPathBeanDefinitionScanner的doScan函數:
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {Assert.notEmpty(basePackages, "At least one base package must be specified");//BeanDefinitionHolder的容器Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();for (String basePackage : basePackages) {//選擇候選者Set<BeanDefinition> candidates = findCandidateComponents(basePackage);for (BeanDefinition candidate : candidates) {ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);candidate.setScope(scopeMetadata.getScopeName());String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);//如果是基包下的一個抽象類別,我們配置的mapper介面如果不是註解方式也會走這處理if (candidate instanceof AbstractBeanDefinition) {postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);}//如果基包下的類是有註解的if (candidate instanceof AnnotatedBeanDefinition) {AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);}//如果dao包(一般配置的basePakage是這個)下的類是符合mybaits要求的則向spring IOC容器中註冊它的BeanDefinitionif (checkCandidate(beanName, candidate)) {BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);beanDefinitions.add(definitionHolder);registerBeanDefinition(definitionHolder, this.registry);}}}return beanDefinitions;}
ClassPathMapperScanner的doScan函數:
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 {      for (BeanDefinitionHolder holder : beanDefinitions) {        GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();        //此處的mapperInterface就是我們寫的mapper介面一般是個空介面,實際上關聯到它        //的BeanDefinition中的Bean是MapperFactoryBean,MapperFactoryBean很重要        definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());        definition.setBeanClass(MapperFactoryBean.class);        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);        }      }    }    return beanDefinitions;  }

protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {//如果spring中沒註冊這個beanName對應的bean那麼就是mybaits需要的類,一般mybaits的mapper類是一個介面不會被spring執行個體化載入到IOC容器中if (!this.registry.containsBeanDefinition(beanName)) {return true;}//如果spring中有這個類的bean定義BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();if (originatingDef != null) {existingDef = originatingDef;}//如果重複掃描此類或者或者重複擷取同一個類的源檔案或者是其它類的子類則是不相容的,這樣的類是不符合mybaits載入要求返回falseif (isCompatible(beanDefinition, existingDef)) {return false;}throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +"' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +"non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");}

    我們再來看看MapperFactoryBean的checkDaoConfig函數,看它是怎麼將DAO關聯到對應的mapper.xml的:

protected void checkDaoConfig() {//調用父類同名方法    super.checkDaoConfig();    //擷取sqlSessionFactoryBean中設定檔在java中的對象Configuration    //如果沒有mapperInterface的定義則加入此mapper的定義    //此configuration對象是mybaits下的不是spring的哦!    Configuration configuration = getSqlSession().getConfiguration();    if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {      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();      }    }  }

     這樣Mapper介面就被註冊到sqlSession中,每當操作sqlSession時就會根據這個mapperInterface去尋找對應的mapper.xml構建mapper從而完成資料庫操作。

     經過以上過程mybaits找到了所有mapper並將其載入到了spring ioc容器裡,本章也就完結了。下一章我們再講mybaits是怎麼解析mapper.xml的。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.