Mybatis MapperScannerConfigurer 自動掃描 將Mapper接口生成代理注入到Spring
Mybatis在與Spring集成的時候可以配置MapperFactoryBean來生成Mapper接口的代理. 例如
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
MapperFactoryBean 創建的代理類實現了 UserMapper 接口,並且注入到應用程序中。 因為代理創建在運行時環境中(Runtime,譯者注) ,那么指定的映射器必須是一個接口,而 不是一個具體的實現類。
上面的配置有一個很大的缺點,就是系統有很多的配置文件時 全部需要手動編寫,所以上述的方式已經很用了。
沒有必要在 Spring 的 XML 配置文件中注冊所有的映射器。相反,你可以使用一個 MapperScannerConfigurer , 它 將 會 查 找 類 路 徑 下 的 映 射 器 並 自 動 將 它 們 創 建 成 MapperFactoryBean。
要創建 MapperScannerConfigurer,可以在 Spring 的配置中添加如下代碼:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> </bean>
basePackage 屬性是讓你為映射器接口文件設置基本的包路徑。 你可以使用分號或逗號 作為分隔符設置多於一個的包路徑。每個映射器將會在指定的包路徑中遞歸地被搜索到。
注 意 , 沒 有 必 要 去 指 定 SqlSessionFactory 或 SqlSessionTemplate , 因 為 MapperScannerConfigurer 將會創建 MapperFactoryBean,之后自動裝配。但是,如果你使 用了一個 以上的 DataSource ,那 么自動 裝配可 能會失效 。這種 情況下 ,你可 以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 屬性來設置正確的 bean 名 稱來使用。這就是它如何來配置的,注意 bean 的名稱是必須的,而不是 bean 的引用,因 此,value 屬性在這里替代通常的 ref:
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
MapperScannerConfigurer 支 持 過 濾 由 指 定 的 創 建 接 口 或 注 解 創 建 映 射 器 。 annotationClass 屬性指定了要尋找的注解名稱。 markerInterface 屬性指定了要尋找的父 接口。如果兩者都被指定了,加入到接口中的映射器會匹配兩種標准。默認情況下,這兩個 屬性都是 null,所以在基包中給定的所有接口可以作為映射器加載。
被發現的映射器將會使用 Spring 對自動偵測組件(參考 Spring 手冊的 3.14.4)默認的命 名策略來命名。也就是說,如果沒有發現注解,它就會使用映射器的非大寫的非完全限定類 名。但是如果發現了@Component 或 JSR-330 的@Named 注解,它會獲取名稱。注意你可以 配 置 到 org.springframework.stereotype.Component , javax.inject.Named(如果你使用 JSE 6 的話)或你自己的注解(肯定是自我注解)中,這 樣注解將會用作生成器和名稱提供器。
接下來讓我們看一下MapperScannerConfigurer類的源碼 看看是如何自動掃描的。
1 public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { 2 if (this.processPropertyPlaceHolders) { 3 processPropertyPlaceHolders(); 4 } 5 6 ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); 7 scanner.setAddToConfig(this.addToConfig); 8 scanner.setAnnotationClass(this.annotationClass); 9 scanner.setMarkerInterface(this.markerInterface); 10 scanner.setSqlSessionFactory(this.sqlSessionFactory); 11 scanner.setSqlSessionTemplate(this.sqlSessionTemplate); 12 scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName); 13 scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName); 14 scanner.setResourceLoader(this.applicationContext); 15 scanner.setBeanNameGenerator(this.nameGenerator); 16 scanner.registerFilters(); 17 scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); 18 }
把Mapper接口轉換成MapperFactoryBean的代碼在地17行這個方法里,讓我們跟蹤進去看一下。
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 }