SqlSessionFactoryBean详解

371 阅读1分钟

文章目录

官方学习地址

官网:mybatis.org/spring/zh/f…

作用

代码分析

类图:
在这里插入图片描述
继承的接口:

  • 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方法

看buildSqlSessionFactory方法,首先要先看Configuration类:
在这里插入图片描述
大概看一下,发现这个类其实就是我们在mybatis配置文件里面配置的属性,创建SqlSessionFactory实际就是不断给configuration赋值的过程.
在这里插入图片描述
然后后面一大段都是对configuration进行赋值;
详情可以直接看官网:mybatis.org/mybatis-3/z…
我举几个常见的:
在这里插入图片描述
XMLMapperBuilder的主要解析:
在这里插入图片描述

最后就是通过sqlSessionFactoryBuilder来创建SqlSessionFactory;