Spring整合MyBatis(二)源码分析

来源:互联网 发布:男士须后水推荐知乎 编辑:程序博客网 时间:2024/05/17 09:36
在Spring配置Mybatis的文件中我们可以看到如下代码:
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!-- 扫描dao -->  
  2. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  3. <property name="basePackage" value="org.tarena.note.dao">  
  4. </property>  

MapperScannerConfigurer,让它扫描特定的包,自动帮我们成批地创建映射器。这样就大大减少了配置的工作量。

basePackage属性是让你为映射器接口文件设置基本的包路径。可以使用分号或逗号作为分隔符设置多于一个的包路径。每个映射器都会在指定的包路径中递归地被搜索到。被发现的映射器将会使用Spring对自动侦测组件默认的命名策略来命名。也就是说,如果没有发现注解,它就会使用映射器的非大写的非完全限定类名。如果发现了@Component或JSR-330@Named注解,它会获取名称。

通过上面的配置,Spring就会帮助我们对test.mybatis.dao下面所有接口进行自动的注入,而不需要为每个接口重复在Spring配置文件中进行声明了。那么这个功能如何做到的呢?MapperScanner Configurer中又有哪些核心操作呢?同样首先看下这个类实现了InitializingBean接口。马上查找afterPropertiesSet方法来看看类的初始化逻辑。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {  
但没有任何有意义的实现,我们看到MapperScannerConfigurer还实现了接口BeanDefinitionRegistryPostProcessor接口的方法:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  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. }  

正是这里。大致看下代码实现,正是完成了对指定路径扫描的逻辑。那么,我们就以此为入口,详细地分析MapperScannerConfigurer所提供的逻辑实现下载  

1.processPropertyPlaceHolders属性的处理

首先,难题就是processPropertyPlaceHolders属性的处理。或许许多人并未接触过此属性。我们只能查看processPropertyPlaceHolders()函数来反推此属性所代表的功能。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. private void processPropertyPlaceHolders() {  
  2.   Map<String, PropertyResourceConfigurer> prcs = applicationContext.getBeansOfType(PropertyResourceConfigurer.class);  
  3.   
  4.   if (!prcs.isEmpty() && applicationContext instanceof GenericApplicationContext) {  
  5.     BeanDefinition mapperScannerBean = ((GenericApplicationContext) applicationContext)  
  6.         .getBeanFactory().getBeanDefinition(beanName);  
  7.   
  8.     // PropertyResourceConfigurer does not expose any methods to explicitly perform  
  9.     // property placeholder substitution. Instead, create a BeanFactory that just  
  10.     // contains this mapper scanner and post process the factory.  
  11.     DefaultListableBeanFactory factory = new DefaultListableBeanFactory();  
  12.     factory.registerBeanDefinition(beanName, mapperScannerBean);  
  13.   
  14.     for (PropertyResourceConfigurer prc : prcs.values()) {  
  15.       prc.postProcessBeanFactory(factory);  
  16.     }  
  17.   
  18.     PropertyValues values = mapperScannerBean.getPropertyValues();  
  19.   
  20.     this.basePackage = updatePropertyValue("basePackage", values);  
  21.     this.sqlSessionFactoryBeanName = updatePropertyValue("sqlSessionFactoryBeanName", values);  
  22.     this.sqlSessionTemplateBeanName = updatePropertyValue("sqlSessionTemplateBeanName", values);  
  23.   }  
  24. }  

此函数的说明给我嗯进行了说明:BeanDefinitionRegistries会在应用启动的时候调用,并且会早于BeanFactoryPostProcessors的调用,这就意味着PropertiesResourceConfigurers还没有被加载所有对于属性文件的引用将会失效,为避免此种情况发生,此方法手动地找出定义的PropertyResourceConfigurers并进行调用以以保证对于属性的引用可以正常工作。

下面我们举个例子说明:

如果在配置文件中添加如下代码下载  

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <pre name="code" class="java"><bean class="org.mybatis.Spring.mapper.MapperScannerConfigurer">  
  2.       <property name="basePackage" value="${basePackage}"/>  
  3. </bean>  

此时你会发现这个配置并没有生效。因为在解析MapperScannerConfigurer这个bean的时候,配置文件还没有被加载,为了解决这个问题,Spring提供了processPropertyPlaceHloder属性,你需要这样配置MapperScannerConfigurer类型的bean:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <pre name="code" class="java"><bean class="org.mybatis.Spring.mapper.MapperScannerConfigurer">  
  2.       <property name="basePackage" value="${basePackage}"/>  
  3.       <property name="processPropertyPlaceHolders" value="true">  
  4. </bean>  

通过processPropertyPlaceHolders属性的配置,将程序引入我们正在分析的processPropertyPlaceHolders函数中来完成属性文件的加载。至此,我们理清了这个函数的属性,再回顾看下这个函数做的事情:

(1)找到所有已经注册的PropertyResourceConfigurer类型的bean。

(2)模拟Spring的环境来用处理器。这里通过使用呢new DefaultlistableBeanFactory()来模拟Spring中的环境(完成处理器的调用后便失效),将映射的bean,也就是MapperScannerConfigurer类型bean注册到环境中来进行后处理器的调用。

2.根据配置属性生成过滤器下载  

在postProcessBeanDefinitionRegistry方法中可以看到,配置中支持很多属性的设定,但是我们感兴趣的或者说影响扫描结果的并不多,属性设置后通过在scanner.registerFilters()代码中生成对应的过滤器来控制扫描结果。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void registerFilters() {  
  2.   boolean acceptAllInterfaces = true;  
  3.   
  4.   // if specified, use the given annotation and / or marker interface  
  5.   //对于annotationClass属性的处理  
  6.   /* 
  7.    *如果annotationClass不为空,表示用户设置了此属性,那么就要根据此属性生成过滤器以保证达到用户 
  8.    *想要的效果,而封装此属性的过滤器就是AnnotationTypeFilter.AnnotationTypeFilter保证在扫描对应 
  9.    *java文件时只接受标记有注解为annotationClass接口  
  10.    */  
  11.   if (this.annotationClass != null) {  
  12.     addIncludeFilter(new AnnotationTypeFilter(this.annotationClass));  
  13.     acceptAllInterfaces = false;  
  14.   }  
  15.   
  16.   // override AssignableTypeFilter to ignore matches on the actual marker interface  
  17.   //对于markerInterface属性的处理  
  18.   if (this.markerInterface != null) {  
  19.     addIncludeFilter(new AssignableTypeFilter(this.markerInterface) {  
  20.       @Override  
  21.       protected boolean matchClassName(String className) {  
  22.         return false;  
  23.       }  
  24.     });  
  25.     acceptAllInterfaces = false;  
  26.   }  
  27.   //全局默认处理  
  28.   /* 
  29.    * 在上面两个属性中如果存在其中任何属性,acceptAllInterfaces的值将会被改变,但是如果用户没有设定以上的属性 
  30.    * 那么,Spring会为我们增加一个默认的过滤器实现TypeFilter接口的局部类,旨在接受所有接口文件。 
  31.    */  
  32.   if (acceptAllInterfaces) {  
  33.     // default include filter that accepts all classes  
  34.     addIncludeFilter(new TypeFilter() {  
  35.       public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {  
  36.         return true;  
  37.       }  
  38.     });  
  39.   }  
  40.   
  41.   // exclude package-info.java  
  42.   //不扫描package-info.java文件  
  43.   addExcludeFilter(new TypeFilter() {  
  44.     public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {  
  45.       String className = metadataReader.getClassMetadata().getClassName();  
  46.       return className.endsWith("package-info");  
  47.     }  
  48.   });  
  49. }  

从上面的函数我们可以看出,控制扫描文件Spring通过不同的过滤器完成,这些定义的过滤器记录在了includeFilters和excludeFilters属性中。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public void addIncludeFilter(TypeFilter includeFilter){  
  2.        this.includeFilters.add(includeFilter);  
  3. }  
  4.   
  5. public void addExcludeFilter(TypeFilter excludeFilter){  
  6.        this.excludeFilters.add(0,excludeFilter);  
  7. }  

至于过滤器为什么会在扫描过程中起作用,我们在后面分析扫描实现的时候再深入研究。

3.扫描java文件

设置了相关属性以及生成了对应的过滤器后就可以进行文件的扫描了,扫描工作是有ClassPathMapperScanner类的父类ClassPathBeanDefinitionScanner的scan方法完成的。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public int scan(String... basePackages) {  
  2.     int beanCountAtScanStart = this.registry.getBeanDefinitionCount();  
  3.   
  4.     doScan(basePackages);  
  5.   
  6.     // Register annotation config processors, if necessary.  
  7.     if (this.includeAnnotationConfig) {  
  8.         AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);  
  9.     }  
  10.   
  11.     return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);  
  12. }  

scan是个全局方法,扫描工作通过
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. doScan(basePackages);  
委托给了doScan方法,同时,还包括了includeAnnotationConfig属性的处理,AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);代码主要是完成对于注解处理器的简单注册,我们下面主要分析下扫描功能的实现下载  

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Set<BeanDefinitionHolder> doScan(String... basePackages) {  
  2.   Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);  
  3.   
  4.   if (beanDefinitions.isEmpty()) {  
  5.     //没有扫描到任何文件发出警告  
  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.       //开始构造MapperFactoryBean类型的bean.  
  19.       definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());  
  20.       definition.setBeanClass(MapperFactoryBean.class);  
  21.   
  22.       definition.getPropertyValues().add("addToConfig"this.addToConfig);  
  23.   
  24.       boolean explicitFactoryUsed = false;  
  25.       if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {  
  26.         definition.getPropertyValues().add("sqlSessionFactory"new RuntimeBeanReference(this.sqlSessionFactoryBeanName));  
  27.         explicitFactoryUsed = true;  
  28.       } else if (this.sqlSessionFactory != null) {  
  29.         definition.getPropertyValues().add("sqlSessionFactory"this.sqlSessionFactory);  
  30.         explicitFactoryUsed = true;  
  31.       }  
  32.   
  33.       if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {  
  34.         if (explicitFactoryUsed) {  
  35.           logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");  
  36.         }  
  37.         definition.getPropertyValues().add("sqlSessionTemplate"new RuntimeBeanReference(this.sqlSessionTemplateBeanName));  
  38.         explicitFactoryUsed = true;  
  39.       } else if (this.sqlSessionTemplate != null) {  
  40.         if (explicitFactoryUsed) {  
  41.           logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");  
  42.         }  
  43.         definition.getPropertyValues().add("sqlSessionTemplate"this.sqlSessionTemplate);  
  44.         explicitFactoryUsed = true;  
  45.       }  
  46.   
  47.       if (!explicitFactoryUsed) {  
  48.         if (logger.isDebugEnabled()) {  
  49.           logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");  
  50.         }  
  51.         definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);  
  52.       }  
  53.     }  
  54.   }  
  55.   
  56.   return beanDefinitions;  
  57. }  

此时,虽然还没有完成介绍到扫描的过程,但是我们也应该理解了Spring中对于自动扫描的注册,声明MapperScannerConfigurer类型的bean目的是不需要我们对于每个接口都注册一个MapperFactoryBean类型的对应的bean,但是,不再配置文件中注册并不代表这个bean不存在,而是在扫描的过程中通过编码的方式动态注册。实现过程我们在上面的函数中可以看得非常清楚下载  
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected Set<BeanDefinitionHolder> doScan(String... basePackages) {  
  2.     Assert.notEmpty(basePackages, "At least one base package must be specified");  
  3.     Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();  
  4.     for (String basePackage : basePackages) {  
  5.         //扫描basePackage路径下的java文件  
  6.         Set<BeanDefinition> candidates = findCandidateComponents(basePackage);  
  7.         for (BeanDefinition candidate : candidates) {  
  8.             //解析scope属性  
  9.             ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);  
  10.             candidate.setScope(scopeMetadata.getScopeName());  
  11.             String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);  
  12.             if (candidate instanceof AbstractBeanDefinition) {  
  13.                 postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);  
  14.             }  
  15.             if (candidate instanceof AnnotatedBeanDefinition) {  
  16.                 //如果是AnnotationBeanDefinition类型的bean需要检测下常用注解如:Primary,Lazy等。  
  17.                 AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);  
  18.             }  
  19.             //检测当前bean是否已经注册  
  20.             if (checkCandidate(beanName, candidate)) {  
  21.                 BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);  
  22.                 //如果当前bean是用于生成代理的bean那么需要进一步处理  
  23.                 definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);  
  24.                 beanDefinitions.add(definitionHolder);  
  25.                 registerBeanDefinition(definitionHolder, this.registry);  
  26.             }  
  27.         }  
  28.     }  
  29.     return beanDefinitions;  
  30. }  

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public Set<BeanDefinition> findCandidateComponents(String basePackage) {  
  2.     Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();  
  3.     try {  
  4.         String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +  
  5.                 resolveBasePackage(basePackage) + "/" + this.resourcePattern;  
  6.         Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);  
  7.         boolean traceEnabled = logger.isTraceEnabled();  
  8.         boolean debugEnabled = logger.isDebugEnabled();  
  9.         for (Resource resource : resources) {  
  10.             if (traceEnabled) {  
  11.                 logger.trace("Scanning " + resource);  
  12.             }  
  13.             if (resource.isReadable()) {  
  14.                 try {  
  15.                     MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);  
  16.                     if (isCandidateComponent(metadataReader)) {  
  17.                         ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);  
  18.                         sbd.setResource(resource);  
  19.                         sbd.setSource(resource);  
  20.                         if (isCandidateComponent(sbd)) {  
  21.                             if (debugEnabled) {  
  22.                                 logger.debug("Identified candidate component class: " + resource);  
  23.                             }  
  24.                             candidates.add(sbd);  
  25.                         }  
  26.                         else {  
  27.                             if (debugEnabled) {  
  28.                                 logger.debug("Ignored because not a concrete top-level class: " + resource);  
  29.                             }  
  30.                         }  
  31.                     }  
  32.                     else {  
  33.                         if (traceEnabled) {  
  34.                             logger.trace("Ignored because not matching any filter: " + resource);  
  35.                         }  
  36.                     }  
  37.                 }  
  38.                 catch (Throwable ex) {  
  39.                     throw new BeanDefinitionStoreException(  
  40.                             "Failed to read candidate component class: " + resource, ex);  
  41.                 }  
  42.             }  
  43.             else {  
  44.                 if (traceEnabled) {  
  45.                     logger.trace("Ignored because not readable: " + resource);  
  46.                 }  
  47.             }  
  48.         }  
  49.     }  
  50.     catch (IOException ex) {  
  51.         throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);  
  52.     }  
  53.     return candidates;  
  54. }  

findCandidateComponents方法根据传入的包路径信息并结合类文件路径拼接成文件的绝对路径,同时完成了文件的扫描过程并且根据对应的文件生成了对应的bean,使用ScannedGenericBeanDefinition类型的bean承载信息,bean中值记录了resource和source信息。这里,我们更感兴趣的是isCandidateCompanent(metadataReader),此句代码用于判断当前扫描的文件是否符合要求,而我们之前注册的过滤器也是在此派上用场的。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {  
  2.     for (TypeFilter tf : this.excludeFilters) {  
  3.         if (tf.match(metadataReader, this.metadataReaderFactory)) {  
  4.             return false;  
  5.         }  
  6.     }  
  7.     for (TypeFilter tf : this.includeFilters) {  
  8.         if (tf.match(metadataReader, this.metadataReaderFactory)) {  
  9.             AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();  
  10.             if (!metadata.isAnnotated(Profile.class.getName())) {  
  11.                 return true;  
  12.             }  
  13.             AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class);  
  14.             return this.environment.acceptsProfiles(profile.getStringArray("value"));  
  15.         }  
  16.     }  
  17.     return false;  
  18. }  
0 0
原创粉丝点击