Spring整合MyBatis(三)sqlSessionFactory创建

摘要: 本文结合《Spring源码深度解析》来分析Spring 5.0.6版本的源代码。若有描述错误之处,欢迎指正。

目录

一、SqlSessionFactoryBean的初始化

二、获取 SqlSessionFactoryBean 实例

通过Spring整合MyBatis的示例,我们感受到了Spring为用户更加快捷地进行开发所做的努力,开发人员的工作效率由此得到了显著的提升。但是,相对于使用来说,我们更想知道其背后所隐藏的秘密,Spring整合MyBatis是如何实现的呢?通过分析整合示例中的配置文件,我们可以知道配置的bean其实是成树状结构的,而在树的最顶层是类型为org.mybatis.spring.SqlSessionFactoryBean的bean,它将其他相关bean组装在了一起,那么,我们的分析就从此类开始。

通过配置文件我们分析,对于配置文件的读取解析,Spring应该通过org.mybatis.spring.SqlSessionFactoryBean封装了MyBatis中的实现。我们进入这个类,首先査看这个类的层次结构,如下图所示。

根据这个类的层次结构找出我们感兴趣的两个接口,FactoryBean和InitializingBean:

  • InitializingBean:实现此接口的bean会在初始化时调用其afterPropertiesSet方法来进行bean的逻辑初始化。
  • FactoryBean:一旦某个bean实现此接口,那么通过getBean方法获取bean时其实是获取此类的getObject()返回的实例。

我们首先以InitializingBean接口的afterPropertiesSet()方法作为突破点。

一、SqlSessionFactoryBean的初始化

査看org.mybatis.spring.SqlSessionFactoryBean类型的bean在初始化时做了哪些逻辑实现。

@Override
public void afterPropertiesSet() throws Exception {
    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");

    this.sqlSessionFactory = buildSqlSessionFactory();
}

很显然,此函数主要目的就是对于sqlSessionFactory的初始化,通过之前展示的独立使用MyBatis的示例,我们了解到SqlSessionFactory是所有MyBatis功能的基础。

protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

    Configuration configuration;

    XMLConfigBuilder xmlConfigBuilder = null;
    if (this.configuration != null) {
        configuration = this.configuration;
        if (configuration.getVariables() == null) {
            configuration.setVariables(this.configurationProperties);
        } else if (this.configurationProperties != null) {
            configuration.getVariables().putAll(this.configurationProperties);
        }
    } else if (this.configLocation != null) {
        xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
        configuration = xmlConfigBuilder.getConfiguration();
    } else {
        LOGGER.debug(() -> "Property ‘configuration‘ or ‘configLocation‘ not specified, using default MyBatis Configuration");
        configuration = new Configuration();
        if (this.configurationProperties != null) {
            configuration.setVariables(this.configurationProperties);
        }
    }

    if (this.objectFactory != null) {
        configuration.setObjectFactory(this.objectFactory);
    }

    if (this.objectWrapperFactory != null) {
        configuration.setObjectWrapperFactory(this.objectWrapperFactory);
    }

    if (this.vfs != null) {
        configuration.setVfsImpl(this.vfs);
    }

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

    if (!isEmpty(this.typeAliases)) {
        for (Class<?> typeAlias : this.typeAliases) {
            configuration.getTypeAliasRegistry().registerAlias(typeAlias);
            LOGGER.debug(() -> "Registered type alias: ‘" + typeAlias + "‘");
        }
    }

    if (!isEmpty(this.plugins)) {
        for (Interceptor plugin : this.plugins) {
            configuration.addInterceptor(plugin);
            LOGGER.debug(() -> "Registered plugin: ‘" + plugin + "‘");
        }
    }

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

    if (!isEmpty(this.typeHandlers)) {
        for (TypeHandler<?> typeHandler : this.typeHandlers) {
            configuration.getTypeHandlerRegistry().register(typeHandler);
            LOGGER.debug(() -> "Registered type handler: ‘" + typeHandler + "‘");
        }
    }

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

    if (this.cache != null) {
        configuration.addCache(this.cache);
    }

    if (xmlConfigBuilder != null) {
        try {
            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();
        }
    }

    if (this.transactionFactory == null) {
        this.transactionFactory = new SpringManagedTransactionFactory();
    }

    configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));

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

            try {
                XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),
                        configuration, mapperLocation.toString(), configuration.getSqlFragments());
                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");
    }

    return this.sqlSessionFactoryBuilder.build(configuration);
}

从函数中可以看到,尽管我们还是习惯于将MyBatis的配置与Spring的配置独立开来,但是,这并不代表Spring中的配置不支持直接配置。也就是说,在上面提供的示例中,你完全可以取消配置中的configLocation,而把其中的属性直接写在SqlSessionFactoryBean中。

从这个函数中可以得知,配置文件还可以支持其他多种属性的配置,如configLocation、objectFactory、objectWrapperFactory、typeAliasesPackage、typeAliases、typeHandlersPackage、plugins、typeHandlers、transactionFactory、databaseIdProvider、mapperLocations。

其实,如果只按照常用的配置,那么我们只需要在函数最开始按照如下方式处理configuration:

xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();

根据configLocation构造XMLConfigBuilder并进行解析,但是,为了体现Spring更强大的兼容性,Spring还整合了MyBatis中其他属性的注入,并通过实例configuration来承载每一步所获取的信息并最终使用sqlSessionFactoryBuilder实例根据解析到的configuration创建SqlSessionFactory实例。

二、获取 SqlSessionFactoryBean 实例

由于SqlSessionFactoryBean实现了FactoryBean接口,所以当通过getBean方法获取对应实例时,其实是获取该类的getObject()函数返回的实例,也就是获取初始化后的sqlSessionFactory属性。

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

    return this.sqlSessionFactory;
}

原文地址:https://www.cnblogs.com/warehouse/p/9445846.html

时间: 2024-08-14 07:54:13

Spring整合MyBatis(三)sqlSessionFactory创建的相关文章

spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

出bug的原因:mybatis-spring版本问题. 查看SqlSessionDaoSupport源码 1.2以上的版本: 1.1.1版本: 解决方法:1.2版本移除了@Autowired的注解,所以如果是1.2版本以上,要在BaseDaoImpl里面手动 注入SetSessionTemplate或者SetSessionFactory spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property 'sqlSessionFa

Spring整合Mybatis解决 Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

在Spring4和Mybatis3整合的时候,dao层注入'sqlSessionFactory'或'sqlSessionTemplate'会报错解决办法如下: package com.alibaba.webx.MyWebxTest.myWebX.module.dao.impl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.m

spring源码剖析(八)spring整合mybatis原理

前言 MyBatis相信很多人都会使用,但是当MyBatis整合到了Spring中,我们发现在Spring中使用更加方便了.例如获取Dao的实例,在Spring的我们只需要使用注入的方式就可以了使用Dao了,完全不需要调用SqlSession的getMapper方法去获取Dao的实例,更不需要我们去管理SqlSessionFactory,也不需要去创建SqlSession之类的了,对于插入操作也不需要我们commit. 既然那么方便,Spring到底为我们做了哪些工作呢,它如何将MyBatis整

Spring整合MyBatis完整示例

为了梳理前面学习的内容<Spring整合MyBatis(Maven+MySQL)一>与<Spring整合MyBatis(Maven+MySQL)二>,做一个完整的示例完成一个简单的图书管理功能,主要使用到的技术包含Spring.MyBatis.Maven.MySQL及简单MVC等.最后的运行效果如下所示: 项目结构如下: 一.新建一个基于Maven的Web项目 1.1.创建一个简单的Maven项目,项目信息如下: 1.2.修改层面信息,在项目上右键选择属性,再选择“Project

Spring整合Mybatis的注意事项

初学 Spring 整合 Mybatis,虽然网贴无数,但是每次试行下来,总会发生这样那样的问题.最终经过数天的不断尝试,总算是成功运行了,遇到的多数坑也一一绕过,特此记录已备查: 一.关于依赖包 网上的很多帖子杂七杂八加入了各种依赖包,有时看的人头晕脑胀,经过实测,实际需要的依赖包,只有下面三组: <!-- 1.基础Spring依赖 --> <dependency> <groupId>org.springframework</groupId> <ar

spring整合mybatis(hibernate)配置

一.Spring整合配置Mybatis spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位.一般需要具备如下几个基本配置. 1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置) 1 <!-- 导入properties配置文件 --> 2 <context:property-placeholder location="classpath*:/jdbc.prop

Mybatis入门——Spring整合MyBatis

Spring整合MyBatis 对Teacher表进行添加数据和查看数据 1. 创建数据库表 CREATE TABLE `teacher` (  `t_id` varchar(15) NOT NULL,  `t_name` varchar(30) DEFAULT NULL,  PRIMARY KEY (`t_id`)) 2.创建Spring工程 3.导入相关包 mybatis-spring-1.3.0.jar mybatis-3.3.0.jar mysql-connector-java-5.1.

分析下为什么spring 整合mybatis后为啥用不上session缓存

因为一直用spring整合了mybatis,所以很少用到mybatis的session缓存. 习惯是本地缓存自己用map写或者引入第三方的本地缓存框架ehcache,Guava 所以提出来纠结下 实验下(spring整合mybatis略,网上一堆),先看看mybatis级别的session的缓存 放出打印sql语句 configuration.xml 加入 <settings> <!-- 打印查询语句 --> <setting name="logImpl"

Spring整合MyBatis (使用扫描包配置mapper代理)

Spring整合MyBatis (使用扫描包配置mapper代理) pojo是根据表生成的实体类,属性名要跟字段名相同,不相同sql语句查询时用别名. 首先导jar包 实体类 public class User { private Integer id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 } 1 2 3