源码解析:SqlSessionFactoryBean+MapperScannerConfigurer+BasicDataSource

SqlSessionFactoryBean

配置:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
   <!-- mybatis全局配置文件 -->
   <property name="configLocation" value="classpath:mybatis-config.xml"></property>
   <!-- 数据源 -->
   <property name="dataSource" ref="pooledDataSource"></property>
   <!-- mapper文件 -->
   <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>

SqlSessionFactoryBean 从名字就能看出来它是用来创建工厂类的,继承关系如下:

 继承的接口:

  • InitializingBean:这个接口的作用是spring初始化的时候会执行实现了InitializingBean接口的afterPropertiesSet方法;具体怎么执行暂时就不说了;
  • ApplicationListener接口作用是在spring容器执行的各个阶段进行监听,SqlSessionFactoryBean实现这个接口是为了容器刷新的时候,更新sqlSessionFactory;可以自己看下onApplicationEvent方法实现;
  • FactoryBean:实现这个接口表示这个类是一个工厂bean,通常是为了给返回的类进行加工处理的,而且获取类返回的是通过getObj返回的;

看这个类就从入口开始看,通过这个方法afterPropertiesSet;

  @Override
  public void afterPropertiesSet() throws Exception {
    //dataSource是必须要配置的
    notNull(dataSource, "Property 'dataSource' is required");
    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
              "Property 'configuration' and 'configLocation' can not specified with together");

    //主要逻辑都在buildSqlSessionFactory方法,创建sqlSessionFactory,getObject就是返回的sqlSessionFactory 
    this.sqlSessionFactory = buildSqlSessionFactory();
  }

  @Override
  public SqlSessionFactory getObject() throws Exception {
    if (this.sqlSessionFactory == null) {
      afterPropertiesSet();
    }

    return this.sqlSessionFactory;
  }

buildSqlSessionFactory方法

protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
  // 定义了一个Configuration,叫做targetConfiguration。
  final Configuration targetConfiguration;

  XMLConfigBuilder xmlConfigBuilder = null;
  // 判断 Configuration 对象是否已经存在,也就是是否已经解析过。如果已经有对象,就覆盖一下属性
  if (this.configuration != null) {
    targetConfiguration = this.configuration;
    if (targetConfiguration.getVariables() == null) {
      targetConfiguration.setVariables(this.configurationProperties);
    } else if (this.configurationProperties != null) {
      targetConfiguration.getVariables().putAll(this.configurationProperties);
    }
    // 如果 Configuration 不存在,但是配置了 configLocation 属性,
    // 就根据mybatis-config.xml的文件路径,构建一个xmlConfigBuilder对象。
  } else if (this.configLocation != null) {
    xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
    targetConfiguration = xmlConfigBuilder.getConfiguration();
    // 否则,Configuration 对象不存在,configLocation 路径也没有,
    // 只能使用默认属性去构建去给configurationProperties赋值。
  } else {
    LOGGER.debug(() -> "Property 'configuration' or 'configLocation' not specified,using default MyBatis Configuration");
    targetConfiguration = new Configuration();
    Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);
  }
  
  // 基于当前factory 对象里面已有的属性,对targetConfiguration对象里面属性的赋值。
  Optional.ofNullable(this.objectFactory).ifPresent(targetConfiguration::setObjectFactory);
  Optional.ofNullable(this.objectWrapperFactory).
                 ifPresent(targetConfiguration::setObjectWrapperFactory);
  Optional.ofNullable(this.vfs).ifPresent(targetConfiguration::setVfsImpl);

  if (hasLength(this.typeAliasesPackage)) {
    String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
        ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    Stream.of(typeAliasPackageArray).forEach(packageToScan -> {
      targetConfiguration.getTypeAliasRegistry().registerAliases(packageToScan,
          typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
      LOGGER.debug(() -> "Scanned package: '" + packageToScan + "' for aliases");
    });
  }

  if (!isEmpty(this.typeAliases)) {
    Stream.of(this.typeAliases).forEach(typeAlias -> {
      targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
      LOGGER.debug(() -> "Registered type alias: '" + typeAlias + "'");
    });
  }

  if (!isEmpty(this.plugins)) {
    Stream.of(this.plugins).forEach(plugin -> {
      targetConfiguration.addInterceptor(plugin);
      LOGGER.debug(() -> "Registered plugin: '" + plugin + "'");
    });
  }

  if (hasLength(this.typeHandlersPackage)) {
    String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,
        ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    Stream.of(typeHandlersPackageArray).forEach(packageToScan -> {
      targetConfiguration.getTypeHandlerRegistry().register(packageToScan);
      LOGGER.debug(() -> "Scanned package: '" + packageToScan + "' for type handlers");
    });
  }

  if (!isEmpty(this.typeHandlers)) {
    Stream.of(this.typeHandlers).forEach(typeHandler -> {
      targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
      LOGGER.debug(() -> "Registered type handler: '" + typeHandler + "'");
    });
  }

  if (this.databaseIdProvider != null) {//fix #64 set databaseId before parse mapper xmls
    try {
      targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
    } catch (SQLException e) {
      throw new NestedIOException("Failed getting a databaseId", e);
    }
  }

  Optional.ofNullable(this.cache).ifPresent(targetConfiguration::addCache);
  // 如果xmlConfigBuilder 不为空,也就是上面的第二种情况,
  if (xmlConfigBuilder != null) {
    try {
      // 调用了xmlConfigBuilder.parse()去解析配置文件,最终会返回解析好的Configuration对象
      xmlConfigBuilder.parse();
      LOGGER.debug(() -> "Parsed configuration file: '" + this.configLocation + "'");
    } catch (Exception ex) {
      throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);
    } finally {
      ErrorContext.instance().reset();
    }
  }

  // 如果没有明确指定事务工厂 ,默认使用pringManagedTransactionFactory。
  // 它创建的 SpringManagedTransaction 也有getConnection()和close()方法
  // <property name="transactionFactory" value="" />
  targetConfiguration.setEnvironment(new Environment(this.environment,
      this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory,this.dataSource));

  if (!isEmpty(this.mapperLocations)) {
    for (Resource mapperLocation : this.mapperLocations) {
      if (mapperLocation == null) {
        continue;
      }

      try {
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
         targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
        // 调用xmlMapperBuilder.parse(),
        // 它的作用是把接口和对应的MapperProxyFactory 注册到MapperRegistry 中。
        xmlMapperBuilder.parse();
      } catch (Exception e) {
        throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + e);
      } finally {
        ErrorContext.instance().reset();
      }
      LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'");
    }
  } else {
    LOGGER.debug(() -> "Property 'mapperLocations' was not specified or no matching resources found");
  }

  // 最后调用 sqlSessionFactoryBuilder.build() 返回一个 DefaultSqlSessionFactory。
  return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}

 可以看到最终返回一个 SqlSessionFactory 的默认实现 DefaultSqlSessionFactory。

MapperScannerConfigurer

在spring-mybatis整合过程中,需要将mybatis注入到spring中,这就需要在配置文件中进行配置,这里讲一下org.mybatis.spring.mapper.MapperScannerConfigure的作用:

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描dao包,将mapper接口动态的实例化-->
		<property name="basePackage" value="cn.edu.ujn.ch10.dao" />
        <!--注入sqlSessionFactory-->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

以上代码理解:

1、通过MapperScannerConfigurer来扫描Dao包里面的mapper接口,动态的将mapper接口进行实例化;

2、并将sqlSessionFactory注入到mapper实例中并自动创建sqlsession。

    <!--创建SqlSessionTemplate接口的实例sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--构造方式将sqlSessionFactory注入到SqlSessionTemplate中-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
 
 
    <!--创建Mapper接口的实例MapperImpl-->
    <bean id="Mapper" class="dao.MapperImpl">
        <!--注入sqlSession-->
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

BasicDataSource

1,连接池创建
BasicDataSource ->  DataSource
    @Override 
    public Connection getConnection()
        【a】 createDataSource()
              如果 dataSource不为空,则返回数据源对象,否则创建之,如下:
            【1】 createConnectionFactory()    
                    (a)通过配置参数 <property name="driverClassName" value="${jdbc.driver}" />,加载驱动类 Class.forName(driverClassName);
                    (b)通过配置参数 <property name="url" value="${jdbc.url}" />,获取驱动 DriverManager.getDriver(url);
                    (c)通过配置参数 <property name="username" value="${jdbc.username}" />, <property name="password" value="${jdbc.password}" />,
                    以及 driver,url,创建 数据库连接工厂 new DriverConnectionFactory(driver, url, connectionProperties);
            【2】 createConnectionPool()
                    (a)通过配置参数: <property name="maxActive" value="${dbcp.maxActive}" />
                                            <property name="maxIdle" value="${dbcp.maxIdle}" />
                                            <property name="minIdle" value="${dbcp.minIdle}" />
                                            等配置项,创建连接池org.apach.commons.pool.impl. GenericObjectPool  connectionPool
                                            commons-dbcp本身不创建连接池,通过commons-pool来管理连接池
                    (b)GenericObjectPool. addObject()中调用下步创建的连接池工厂类,创建连接,并通过 addObjectToPool(obj, false);将连接保存在连接池
            【4】 createPoolableConnectionFactory(driverConnectionFactory, statementPoolFactory, abandonedConfig)
                    (a)创建连接池工厂类 PoolableConnectionFactory,工厂类内部将该工厂设置到上步创建的 connectionPool中,这样就可以通过connectionPool中的 addObject()调用连接池工厂创建连接
            【5】 createDataSourceInstance()
                    (a)根据连接池connectionPool创建池化数据源对象  PoolingDataSource pds = new PoolingDataSource(connectionPool)
            【6】初始化连接
                    for (int i = 0 ; i < initialSize ; i++) {
                        connectionPool.addObject();
                    }
            【7】返回池化数据库连接对象 dataSource
        【b】 getConnection()
            【1】 _pool.borrowObject();调用【a】-【2】创建的连接池创建连接
                    (a) _factory.makeObject();调用【a】-【4】创建的连接池工厂类对象,返回 new PoolableConnection(conn,_pool,_config);对象
                            其中 PoolableConnection持有【a】-【2】创建的连接池 _pool ,当 PoolableConnection.close()时,该连接会被 _pool回收, _pool.returnObject(this);

【MyBatis】Spring集成原理(一):分析注入 SqlSessionFactoryBean_槑!的博客-CSDN博客

DBCP连接池:BasicDataSource源码解读_basicdatasource详解_乔布斯基的博客-CSDN博客 

Mybatis MapperScannerConfigurer类初步解析_我叫周利东的博客-CSDN博客

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值