Mybatis源码解析之Spring获取Mapper过程

MyBatis是一款优秀的持久层构架,它支持定制化SQL语句、存储过程以及高级映射,可以通过简单的XML或注解配置和映射原生信息,将POJOs映射成数据库中的记录,从而方便进行增删改查的操作(官网)

问题

Spring如何与MyBatis连接起来的?如何去获取Mybatis中的Mapper,以及获取Mapper时干了哪些骚操作?

为了弄清楚上述问题,菜菜首先贴出开发时主要用到的MyBatis配置,随后进行源码解读,本文采用的是注解式配置。
一般MyBatis的配置如下所示:

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource({"classpath:jdbc.properties"})
@MapperScan(basePackages = "me.ele.eliter.**.mapper")
public class MyBatisConfig {
  private static final Log LOG = LogFactory.getLog(MyBatisConfig.class);

  @Bean(destroyMethod = "close")
  public DataSource dataSource(
      @Value("${db.driver}") String driverClass,
      @Value("${db.url}") String jdbcUrl,
      @Value("${db.username}") String userName,
      @Value("${db.password}") String passWord) throws Exception {
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass(driverClass);
    dataSource.setJdbcUrl(jdbcUrl);
    dataSource.setUser(userName);
    dataSource.setPassword(passWord);
    return dataSource;
  }

  @Bean
  public PlatformTransactionManager transactionManager(DataSource dataSource) {
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
    dataSourceTransactionManager.afterPropertiesSet();
    return dataSourceTransactionManager;
  }

  @Bean
  public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, ApplicationContext applicationContext) throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource);
    sessionFactory.setConfigLocation(applicationContext.getResource("classpath:mybatis-config.xml"));
    sessionFactory.afterPropertiesSet();
    sessionFactory.setPlugins(new Interceptor[] { new PagerInterceptor()});
    return sessionFactory;
  }

  @Bean
  public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) throws Exception {
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.afterPropertiesSet();
    return transactionTemplate;
  }
}

可以看到MyBatisConfig这个类上有几个重要的注解@Configuration与@MapperScan,
@Configuration是Spring中注解,主要说明该类是配置类,Spring在启动时会执行@Bean的方法,并进行Bean的定义,详细信息请自行搜索。
本文主要讲@MapperScan,首先看MapperScan的定义如下

MapperScan

从上可以看到MapperScan中@Import了MapperScannerRegistrar,MapperScannerRegistrar是MaBatis连接Spring的扫描注册的类,从以下MapperScannerRegistrar源码图中可以看到它实现了Spring中的ImportBeanDefinitionRegistrar并重写registerBeanDefinitions方法,registerBeanDefinitions这个方法会在Spring启动里的refresh()->invokeBeanFactoryPostProcessors里一层一层调用到,具体调用链如下,这样在Spring启动时就进入到了MyBatis中进行扫描了
registerBeanDefinitions调用链
MapperScannerRegistrar源码

接下来看MyBatis扫描干了些什么事?以及如何将这些BeanDefinition注册到IOC容器中。
以下是MapperScannerRegistrar实现registerBeanDefinitions的源码

 @Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

 //1.获取了注解MapperScan中的信息
    AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
  /*2.将Spring中的registry放入scanner中,ClassPathMapperScanner继承了Spring的ClassPathBeanDefinitionScanner,
 在new 的时候调用了ClassPathBeanDefinitionScanner的构造方法,将register传入了ClassPathBeanDefinitionScanner中
*/
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);

 //3.一些属性设置操作
    // this check is needed in Spring 3.1
    if (resourceLoader != null) {
      scanner.setResourceLoader(resourceLoader);
    }

    Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
    if (!Annotation.class.equals(annotationClass)) {
      scanner.setAnnotationClass(annotationClass);
    }

    Class<?> markerInterface = annoAttrs.getClass("markerInterface");
    if (!Class.class.equals(markerInterface)) {
      scanner.setMarkerInterface(markerInterface);
    }

    Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
    if (!BeanNameGenerator.class.equals(generatorClass)) {
      scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass));
    }

    Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
    if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
      scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass));
    }

    scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));
    scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));

    List<String> basePackages = new ArrayList<String>();
    for (String pkg : annoAttrs.getStringArray("value")) {
      if (StringUtils.hasText(pkg)) {
        basePackages.add(pkg);
      }
    }
    for (String pkg : annoAttrs.getStringArray("basePackages")) {
      if (StringUtils.hasText(pkg)) {
        basePackages.add(pkg);
      }
    }
    for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {
      basePackages.add(ClassUtils.getPackageName(clazz));
    }
    scanner.registerFilters();
 //4.具体执行扫描
    scanner.doScan(StringUtils.toStringArray(basePackages));
  }

从上面源码中可以看到在Spring调用registerBeanDefinitions时传入了BeanDefinitionRegistry(registry),有了registry就可以将MyBatis中的Mapper的BeanDefinition信息注册到Spring的IOC容器中,下面具体看下registerBeanDefinitions源码,首先是获取了MapperScan注解中的属性信息,接着将Sping中的register传入scanner,这样可将scanner扫描到的BeanDefinition信息注册到IOC容器中,最后是具体的扫描操作,下面看下ClassPathMapperScanner中具体扫描操作的源码

@Override
  public Set<BeanDefinitionHolder> doScan(String... basePackages) {
/*首先调用了Spring中的ClassPathBeanDefinitionScanner扫描类进行扫描得到了具体的beanDefinitions信息,
这一步也将扫描到的beanDefinitions信息注册到了Spring的IOC容器中,这里就不进入Spring源码看了*/
    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 {
      //这里是MyBatis对这些BeanDefinition做了一系列操作为MyBatis的特性服务
      processBeanDefinitions(beanDefinitions);
    }

    return beanDefinitions;
  }

  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
    /*这里获取到的是Mapper的接口,设置这些Mapper接口的实现类默认为MapperFactoryBean,偷天换日,
    (非常重要)下一篇文章中说明为什么Mapper不用写接口实现类就能运行会再次讲到这*/
definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
      definition.setBeanClass(this.mapperFactoryBean.getClass());

      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() + "'.");
        }
    //这里设置Bean中的属性自动根据Type注入
   //(非常重要,后面的一些属性的注入, 如sqlSessionFactory会自动注入全仗于此)
     definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
      }
    }
  }

ClassPathMapperScanner继承了Spring的ClassPathBeanDefinitionScanner,doScan方法
1.调用了ClassPathBeanDefinitionScanner里的doScan方法(扫描方式与Spring的扫描一致),以上MapperScannerRegistrar源码注释2说明了ClassPathBeanDefinitionScanner拥有了Spring的register,这样在得到MyBatis的Mapper后,就可将其中的BeanDefinition注册到Spring中。
2.通过调用processBeanDefinitions对BeanDefinition做了一些重要处理
2.1 definition.setBeanClass(this.mapperFactoryBean.getClass())设置Mapper接口的class对象或是类的全限定名为MapperFactoryBean(可以理解为实现是MapperFactoryBean),这里是MyBatis只用写接口不用写实现的第一步,具体做是通过JDK动态代理,具体细节见Mybatis源码解析之MapperProxy

2.2 definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE设置了这个bean中的属性是根据Type自动注入,加上2.1后这个也就是说会自动调用MapperFactoryBean中的set方法,sqlSessionFactory就是通过这种方式注入的,进而得到sqlSesion,这方面的详细信息见Mybatis源码解析之SqlSession来自何方

至此,Spring中已经获取到了MyBatis有哪些mapper,并且这些mapper接口的BeanDefinition信息经过了MaBatis的处理,比如设置接口的默认实现类为MapperFactoryBean等等,下一步就是解析MaBatis中配置的xml信息

如有错误,欢迎各位大佬斧正!
[下一篇]:Mybatis源码解析之配置解析

推荐阅读更多精彩内容