【MyBatis】Spring整合原理

MyBatis可以独立于Spring使用,这里我们关注一下Mybatis和Spring是怎么整合在一起的。在Spring中使用MyBatis时我们只需要定义一个mapper接口,并配置好对应的mapper.xml,这样就可以直接通过mapper接口直接执行数据库操作。但是我们并没有手动的实例化该接口,那它是如何进行实例化并加入spring容器的呢?

配置文件入手




        
            
                classpath:jdbc.properties
            
        

        
            
            
            
            
            
            
            
            
            
            
            
            
            
            
        

        
            
            
        

        
        
        
        
            
        

MapperScannerConfigurer

与Spring整合的时候配置了两个类org.mybatis.spring.SqlSessionFactoryBeanorg.mybatis.spring.mapper.MapperScannerConfigurer
SqlSessionFactoryBean的对mapper.xml的处理可以参考【MyBatis】mapper.xml解析及annotation支持源码分析,下面分析一下MapperScannerConfigurer到底做了些什么。

【MyBatis】Spring整合原理_第1张图片
MapperScannerConfigurer.png

由上图可以看出这个类实际上实现了几个Spring的接口。查看他的实现的方法,似乎只有postProcessBeanDefinitionRegistry()里有我们关心的内容,这个方法会在BeanDefinition注册后调用,这是还没有创建bean的实例。

@Override
  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    if (this.processPropertyPlaceHolders) {
      //提前处理PropertyPlaceHolder
      processPropertyPlaceHolders();
    }
    //创建一个ClassPathMapperScanner对象,配置扫描包、sqlSessionFactory等
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    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();
    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }
@Override
  public void afterPropertiesSet() throws Exception {
    notNull(this.basePackage, "Property 'basePackage' is required");
  }

@Override
  public void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void setBeanName(String name) {
    this.beanName = name;
  }

postProcessBeanDefinitionRegistry()中的大致逻辑是创建一个ClassPathMapperScanner对象,调用父类ClassPathBeanDefinitionScanner.scan()(ClassPathBeanDefinitionScanner
是Spring中的对象)其中会调用ClassPathBeanDefinitionScanner.doScan()方法来扫描我们配置的package,并封装成beanDefinition加入Spring容器,并返回所有扫描到的beanDefinition。由于子类ClassPathMapperScanner重写了doScan方法,所以最终会调用ClassPathMapperScanner.doScan();

ClassPathMapperScanner

【MyBatis】Spring整合原理_第2张图片
image.png

ClassPathMapperScanner.doScan调用父类的doScan方法(扫描我们配置的package,并封装成beanDefinition加入Spring容器)然后调用processBeanDefinitions处理beanDefinitions,处理过程包含如下几个方面:

  1. beanDefinition中保存了bean的构造方法参数ConstructorArgumentValues,在构造方法参数新增传入原mapper接口
  2. 将beanDefinition的BeanClass属性统一改为org.mybatis.spring.mapper.MapperFactoryBean
  3. 将beanDefinition的属性新增sqlSessionFactory或者sqlSessionTemplate
//org.mybatis.spring.mapper.ClassPathMapperScanner#doScan
@Override
  public Set doScan(String... basePackages) {
    //所有扫描到的BeanDefinitionHolder放入beanDefinitions集合中
    Set beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
      logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
    } else {
      //统一处理扫描到的beanDefinitions
      processBeanDefinitions(beanDefinitions);
    }

    return beanDefinitions;
  }

  private void processBeanDefinitions(Set 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
      //definition中保存的构造方法参数传入原mapper的类名
      definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
      //definition的class全部统一为MapperFactoryBean.class
      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) {
         //传入sqlSessionFactory
        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);
      }
    }
  }

MapperFactoryBean

我们可以思考下通过这些处理以后对Spring容器实例化这些扫描到的bean有什么影响?

  • 首先Spring会使用beanDefinition的beanClass创建实例,这里的beanClass是org.mybatis.spring.mapper.MapperFactoryBean,所以会创建一个MapperFactoryBean对象,而且在调用构造方法创建它的时候会传入构造方法参数ConstructorArgumentValues,即传入mapper的接口。MapperFactoryBean.mapperInterface就是扫描到的mapper接口
  public MapperFactoryBean(Class mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
  • 我们由类图还发现MapperFactoryBean这个类实现了FactoryBean接口,Spring会调用FactoryBean.getObeject来获取真实的bean并注册到容器中,所以这里真实注册的bean应该是getSqlSession().getMapper(this.mapperInterface);获取到的对象。
    【MyBatis】Spring整合原理_第3张图片
    image.png
/**
   * {@inheritDoc}
   */
  @Override
  public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }

MapperFactoryBean继承自SqlSessionDaoSupport,所以getSqlSession其实是调用父类的方法。在父类初始化sqlSessionFactory的时候创建sqlSession即this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);

//public abstract class SqlSessionDaoSupport extends DaoSupport {
  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    if (!this.externalSqlSession) {
      this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  public SqlSession getSqlSession() {
    return this.sqlSession;
  }

}

SqlSessionTemplate.getMapper

SqlSessionTemplate.getMapper-》Configuration.getMapper-》mapperRegistry.getMapper

//org.mybatis.spring.SqlSessionTemplate#getMapper
@Override
  public  T getMapper(Class type) {
    return getConfiguration().getMapper(type, this);
  }

public class Configuration {
  
  public  T getMapper(Class type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
}

public class MapperRegistry {
  @SuppressWarnings("unchecked")
  public  T getMapper(Class type, SqlSession sqlSession) {
    final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
  public  void addMapper(Class type) {
    if (type.isInterface()) {
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
        knownMappers.put(type, new MapperProxyFactory(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }
}

MapperRegistry.getMapper会从knownMappers取,addMapper的时候会往knownMappers里加数据,而addMapper的则是在Mybatis的xml解析及注解支持那部分调用的(可以参考【MyBatis】mapper.xml解析及annotation支持源码分析),每一个mapperInterface对应一个MapperProxyFactory,取出的对象是对应的mapperProxyFactory;

MapperProxyFactory

public class MapperProxyFactory {
  private final Class mapperInterface;
  private final Map methodCache = new ConcurrentHashMap();
  public MapperProxyFactory(Class mapperInterface) {
    this.mapperInterface = mapperInterface;
  }
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy mapperProxy) {
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
}

Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy) 最终产生动态代理代码中代理接口就是mapperInterface,而InvocationHandler是mapperProxy。我们调用mapper接口方法的时候其实会调用到mapperProxy.invoke,这部分在后面分析Sql执行流程的时候再来分析。
至此扫描配置的包路径下所有mapper接口都会通过getSqlSession().getMapper(this.mapperInterface);生成一个bean注册到Spring容器中。所以通过@Autowired 等注解注入的mapper接口的实例其实就是通过getSqlSession().getMapper(this.mapperInterface);生成的一个代理对象,调用这个代理对象执行数据库操作的时候会调用mapperProxy.invoke

你可能感兴趣的:(【MyBatis】Spring整合原理)