Spring+Mybatis学习之Mapper初始化注入Spri

2019-07-15  本文已影响0人  Storydo

最近想扩展一下Mapper的一些功能,查看了一下Mybatis的源码,这里用到的Java框架是Spring Boot,然后整合Mybatis,为了扩展一些基本Sql,使用了github上的abel533/Mapper,这个框架像是一位中国同胞写的,大部分注释使用的中文,其中部分代码为了扩展mybatis的功能,对mybatis框架中的原有部分进行了修改重写。该jar包是在Mybatis的基础上,封装了部分常用的sql,使部分常用的sql没必要每个文件都再写一遍,减少了大量无用代码。

mybatis在github上的地址https://github.com/mybatis/mybatis-3
mybatis说明文档http://www.mybatis.org/mybatis-3/zh/index.html

这里只写一部分Mapper的接口如何注入到Spring容器中,其余的源码之后再写。这部分tk.Mapper中的代码基本与mybatis-spring中的代码一致,看懂一边就可以。

spring boot启动

spring boot大大简化了之前springMVC框架中需要的大量XML配置文件,这里引入jar包就能直接启用Mapper框架了

<dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.1.5</version>
</dependency>

这里启动mapper框架主要是两个类: MapperAutoConfigurationMapperScan

MapperAutoConfiguration扫描

这个类在spring-boot-autoconfigur jar包下,这个类由于使用了spring的注解@Configuration而注入到spring容器中,这里还有两个关键的类也从这里注入到容器中SqlSessionFactorySqlSessionTemplate

MapperScan扫描

这里用的扫描类ClassPathMapperScannerMapperAutoConfiguration中用的扫描类一样,MapperAutoConfiguration这个内部是根据环境配置文件来扫描相关Bean,MapperScan根据注解中的属性来扫描相关的Bean.

ClassPathMapperScanner扫描

上边说的两种方式都是使用该类来扫描相关package包下的接口。并且配置的相关包下所有接口无论是否有注解或者继承自某个Mapper都会注入到spring容器中,该类继承自spring框架中的ClassPathBeanDefinitionScanner

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 {
     processBeanDefinitions(beanDefinitions);
}

上边doScan扫描方法内部调用父类Spring中的扫描方法,返回BeanDefinitionHolder集合。如果集合不为空则会处理相关扫描到的接口。

definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
definition.setBeanClass(this.mapperFactoryBean.getClass());

循环处理所有扫描到的对象,在这里替换掉了原有BeanClass,如果不做设置默认替换成的是MapperFactoryBean,并且将扫描到的接口类作为构造函数的一个参数传入。之后是如果配置了相关的sqlSessionFactorySqlSession就使用配置的,如果没有配置就使用默认的。

definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

如果没有配置sqlSessionFactory,则通过设置上边的definition的一个属性,Spring容器会在实例化Bean时,通过TYPE类型为其自动注入相关的属性。

MapperFactoryBean转化为Bean对象

GenericBeanDefinition是Spring中的类,对象设置后,替换成MapperFactoryBean,该类继承自SqlSessionDaoSupport,实现了接口FactoryBean,这里有两个方法很关键checkDaoConfiggetObject

Configuration configuration = getSqlSession().getConfiguration();
        if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
            try {
                configuration.addMapper(this.mapperInterface);
            } catch (Exception e) {
                logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
                throw new IllegalArgumentException(e);
            } finally {
                ErrorContext.instance().reset();
            }
        }

Configuration中有一个实例化的MapperRegistry,最终将该接口添加MapperRegistry中的map中,键使用当前接口类,值是实例化了一个MapperProxyFactory对象。
在添加接口到注册器当中的同时,这里还做了一件事件,就是将该接口同一目录的xml文件导入进来。

      knownMappers.put(type, new MapperProxyFactory<T>(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;

parser.parse()方法

 if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
      String xmlResource = type.getName().replace('.', '/') + ".xml";
      InputStream inputStream = null;
      try {
        inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
      } catch (IOException e) {
        // ignore, resource is not required
      }
      if (inputStream != null) {
        XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
        xmlParser.parse();
      }
    }

如果不在同一目录下,则其余xml文件是通过环境变量中的配置添加进来的。

    /**
     * Return an instance (possibly shared or independent) of the object
     * managed by this factory.
     * <p>As with a {@link BeanFactory}, this allows support for both the
     * Singleton and Prototype design pattern.
     * <p>If this FactoryBean is not fully initialized yet at the time of
     * the call (for example because it is involved in a circular reference),
     * throw a corresponding {@link FactoryBeanNotInitializedException}.
     * <p>As of Spring 2.0, FactoryBeans are allowed to return {@code null}
     * objects. The factory will consider this as normal value to be used; it
     * will not throw a FactoryBeanNotInitializedException in this case anymore.
     * FactoryBean implementations are encouraged to throw
     * FactoryBeanNotInitializedException themselves now, as appropriate.

也就是说实际注入容器的是该方法返回的值,而不是MapperFactoryBean,getObject实际是调用MapperRegistry中的getMapper

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) 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);
    }
  }

这里实际是返回Proxy.newProxyInstance生成的代理对象,实现了参数type的接口,代理方法是执行MapperProxy中的方法。
至此实例化了所有的接口。将接口实例化后的实例注入到了Spring容器中。

如有错误,欢迎指出,以免影响他人!

上一篇 下一篇

猜你喜欢

热点阅读