Springboot整合MyBatis, yml配置,超详细从mybatis-spring-boot-starter根据源码进行配置,MybatisProperties类中的属性【源码版】)

都知道springboot整合第三方框架,我们开发者使用的时候,大部分都是只需要在pom文件中导入相关的start依赖即可,springboot提供的start能够无缝的整合第三方框架,今天我们就来看一下mybatis-spring-boot-starter中的自动装配。

这些配置都是依赖于mybatis原生的配置,如果不清楚,那么可以看我Springboot整合MyBatis的xml版的一系列文章,该有的都有

首先我们看一下mybatis-spring-boot-starter这个依赖他帮我们管理了哪些依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot</artifactId>
    <version>1.3.2</version>
  </parent>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <name>mybatis-spring-boot-starter</name>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
    </dependency>
  </dependencies>
</project>

从中我们可以看出他帮我们管理的依赖是:
mybatis-spring-boot-autoconfigure:自动装配依赖
mybatis:mybatis原生的依赖
mybatis-spring:结合spring使用的依赖

那么我们主要讲一下mybatis-spring-boot-autoconfigure:

我们打开mybatis-spring-boot-starter源码包下面,找到META-INF\spring.factories(这个文件springboot会扫码,并且读取里面的内容,然后将其类中的配置)

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

然后我们找到这个类:

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {}

这些是这个类上面的注解:

  • @org.springframework.context.annotation.Configuration:spring的配置注解,spring他会将该类加入到spring容器中
  • @ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class }):spring的注解,意思是,只有当SqlSessionFactory.class, SqlSessionFactoryBean.class这两个类的示例都存在的时候,才会将MybatisAutoConfiguration 注入到spring容器中。可能MybatisAutoConfiguration 需要SqlSessionFactory和SqlSessionFactoryBean这两个类的实例
  • @ConditionalOnBean(DataSource.class):当DataSource存在时,才才会将MybatisAutoConfiguration 注入到spring容器中
  • @EnableConfigurationProperties(MybatisProperties.class):开启properties配置。并将MybatisProperties注册到spring上下文中。
  • @AutoConfigureAfter(DataSourceAutoConfiguration.class):该配置类在DataSourceAutoConfiguration加载之后再加载

从这几个注解来看,我们重点关注**@EnableConfigurationProperties**注解,因为他关系到我们的配置。
然后我们去看一下MybatisProperties类的源码(我们所有的配置项,都在里面的属性里面)。

看类上面的注解以及变量值:

@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
 	public static final String MYBATIS_PREFIX = "mybatis";
}

可以看出,在properties中,要配置myabtis,前缀必须是mybatis

然后看里面的属性 (每一个属性在代码层面都打上有详细的注释):

package org.mybatis.spring.boot.autoconfigure;

/**
 * Configuration properties for MyBatis.
 *
 * @author Eddú Meléndez
 * @author Kazuki Shimizu
 */
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {

  public static final String MYBATIS_PREFIX = "mybatis";

  /**
   * 本地mybatis的配置文件,如果我们用xml方式配置的话,他就会去加载这个配置文件
   */
  private String configLocation;

  /**
   * 本地的mapper的映射文件:UserMapper.java  -> classpath:mapper/UserMapper.xml
   * 这是一个数组,可以写多个位置
   */
  private String[] mapperLocations;

  /**
   * mybatis的别名包配置,如果有多个,可以使用 , ; \t\n 其中一种符号分隔开
   */
  private String typeAliasesPackage;

  /**
   * 自定义数据类型转换器的报名,如果多个可以使用 , ; \t\n 其中一种符号分隔开
   */
  private String typeHandlersPackage;

  /**
   * 指示是否对MyBatis xml配置文件执行状态检查,这里默认为false
   */
  private boolean checkConfigLocation = false;

  /**
   * defaultExecutorType的配置项,可选值:SIMPLE, REUSE, BATCH。
   */
  private ExecutorType executorType;

  /**
   * 配置的一些map值
   */
  private Properties configurationProperties;
  
  /**
   * 这个就是mybatis的config配置文件了,如果我们设置了configLocation,自己配置的xml文件,那么该对象就不会被使用。
   */
  @NestedConfigurationProperty
  private Configuration configuration;

}

这个是mybatis的一级配置,然后我们下面重点来关注configuration这个二级配置,他才是mybatis配置的核心,上面的配置只是和springboot结合使用的一些基本配置。

package org.apache.ibatis.session;
public class Configuration {
  // mybatis的环境对象,指定数据源,数据库软件,事物管理器等等。这里就不细说了,
  protected Environment environment;
  // 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。
  protected boolean safeRowBoundsEnabled;
  // 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。
  protected boolean safeResultHandlerEnabled = true;
  // java的驼峰与数据库的下划线做映射,没有给默认值,boolean的默认值是false,所以默认不开启
  protected boolean mapUnderscoreToCamelCase;
  // 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods)。
  protected boolean aggressiveLazyLoading;
  // 是否允许单个语句返回多结果集(需要数据库驱动支持)
  protected boolean multipleResultSetsEnabled = true;
  // 允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。
  protected boolean useGeneratedKeys;
  // 使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。
  protected boolean useColumnLabel = true;
  // 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。
  protected boolean cacheEnabled = true;
  // 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。
  protected boolean callSettersOnNulls;
  // 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1)
  protected boolean useActualParamName = true;
  // 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2)
  protected boolean returnInstanceForEmptyRow;
  // 指定 MyBatis 增加到日志名称的前缀。
  protected String logPrefix;
  // 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。可选值:SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
  protected Class <? extends Log> logImpl;
  // 指定 VFS 的实现。自定义 VFS 的实现的类全限定名。
  protected Class <? extends VFS> vfsImpl;
  // MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。
  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
  // 没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。
  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
  // 指定对象的哪些方法触发一次延迟加载。
  protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));
  // 设置超时时间,它决定数据库驱动等待数据库响应的秒数。
  protected Integer defaultStatementTimeout;
  // 为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。
  protected Integer defaultFetchSize;
  // 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 
  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
  // 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。
  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
  // 指定发现自动映射目标未知列(或未知属性类型)的行为。NONE: 不做任何反应 WARNING: 输出警告日志 FAILING: 映射失败 (抛出 SqlSessionException)
  protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;
  // 变量
  protected Properties variables = new Properties();
  protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
  protected ObjectFactory objectFactory = new DefaultObjectFactory();
  protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();
  // 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。
  protected boolean lazyLoadingEnabled = false;
  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); 
  protected String databaseId;

  protected Class<?> configurationFactory;

  // 下面这几个是注册器,我们无法配置。在通过java的方式可以进行修改,因为这是springboot项目,像比如插件,类型转换器,语言驱动器等这些得通过java代码以及注解来进行操作。
  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  protected final InterceptorChain interceptorChain = new InterceptorChain();
  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();

  protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection");
  protected final Map<String, Cache> caches = new StrictMap<Cache>("Caches collection");
  protected final Map<String, ResultMap> resultMaps = new StrictMap<ResultMap>("Result Maps collection");
  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<ParameterMap>("Parameter Maps collection");
  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<KeyGenerator>("Key Generators collection");

  protected final Set<String> loadedResources = new HashSet<String>();
  protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");

  protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<XMLStatementBuilder>();
  protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<CacheRefResolver>();
  protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>();
  protected final Collection<MethodResolver> incompleteMethods = new LinkedList<MethodResolver>();
}

以上这些配置项都是可以通过yml或者properties来进行配置的:
一下举个例子:
yml格式的:

mybatis:   #顶层
  config-location: "classpath:mybatis-config.xml"  # 一级配置
  mapper-locations: "classpath:mapper/*Mapper.xml" # 一级配置
  configuration: #一级配置
    cache-enabled: true  #二级配置

properties格式的:

mybatis.config-location="classpath:mybatis-config.xml"
mybatis.mapper-locations="classpath:mapper/*Mapper.xml"
mybatis.configuration.cache-enabled=true

下一篇文章我把所有的配置项都提取出来并且打上注释

猜你喜欢

转载自blog.csdn.net/qq_42154259/article/details/107040103