1. 程式人生 > >Mybatis MapperScannerConfigurer 自動掃描 將Mapper介面生成代理注入到Spring

Mybatis MapperScannerConfigurer 自動掃描 將Mapper介面生成代理注入到Spring

複製程式碼
 1   @Override
 2   public Set<BeanDefinitionHolder> doScan(String... basePackages) {
 3     Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
 4 
 5     if (beanDefinitions.isEmpty()) {
 6       logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
7 } else { 8 for (BeanDefinitionHolder holder : beanDefinitions) { 9 GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition(); 10 11 if (logger.isDebugEnabled()) { 12 logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()
13 + "' and '" + definition.getBeanClassName() + "' mapperInterface"); 14 } 15 16 // the mapper interface is the original class of the bean 17 // but, the actual class of the bean is MapperFactoryBean 18 //把介面的型別設定進去 19 definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
20 //設定Bean的真實型別MapperFactoryBean 21 definition.setBeanClass(MapperFactoryBean.class); 22 //是否把Mapper介面加入到Mybatis的Config當中去 23 definition.getPropertyValues().add("addToConfig", this.addToConfig); 24 25 boolean explicitFactoryUsed = false; 26 //如果sqlSessionFactoryBeanName的名字不為空 則在Spring容器中查詢 27 //適合多資料來源 28 if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) { 29 definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName)); 30 explicitFactoryUsed = true; 31 } else if (this.sqlSessionFactory != null) { 32 definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory); 33 explicitFactoryUsed = true; 34 } 35 36 //如果sqlSessionTemplateBeanName的名字不為空 則在Spring容器中查詢 37 //適合多資料來源 38 if (StringUtils.ha 39 if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) { 40 if (explicitFactoryUsed) { 41 logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); 42 } 43 definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName)); 44 explicitFactoryUsed = true; 45 } else if (this.sqlSessionTemplate != null) { 46 if (explicitFactoryUsed) { 47 logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored."); 48 } 49 definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate); 50 explicitFactoryUsed = true; 51 } 52 53 if (!explicitFactoryUsed) { 54 if (logger.isDebugEnabled()) { 55 logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'."); 56 } 57 definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); 58 } 59 } 60 } 61 //這個集合返回以後 Spring容器會將裡面的所有內容註冊到容器中 62 return beanDefinitions; 63 }
複製程式碼