MyBatis 3.4.4 源码分析笔记之xml配置文件初始化SqlSessionFactory核心对象

本文详细解析了MyBatis3.4.4版本中,从XML配置文件初始化SqlSessionFactory对象的核心过程。涵盖配置文件读取、XMLConfigBuilder解析、Configuration对象创建及DefaultSqlSessionFactory实例化等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyBatis 3.4.4 源码分析笔记之xml配置文件初始化SqlSessionFactory核心对象
第一步、给出mybatis的xml配置文件路径
   例如:"org/mybatis/example/Configuration.xml";

配置文件基本格式如下:

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
     <properties></properties>
     <environments>
          <environment></environment>
          .....
     </environments>
     <settings></settings>
     <typeAliases></typeAliases>
     <mappers>
          <mapper resource="mapper文件路径"/>
          .....
     </mappers>
     <plugins></plugins>
</configuration>
第二步、根据配置文件路径,读取XML配置文件,并实例化一个Reader对象
  Reader reader = Resources.getResourceAsReader(resource);
第三步、取得SqlSessionFactory
  sqlSessionFactory = new  SqlSessionFactoryBuilder().build(reader);

** SqlSessionFactoryBuilder的构造方法如下: **

 public SqlSessionFactoryBuilder() {
 
 }

** 其中,build方法源码如下: 删除线格式 **

public SqlSessionFactory build(Reader reader) {
       return this.build((Reader)reader, (String)null, (Properties)null);
   }
 
   public SqlSessionFactory build(Reader reader, String environment) {
       return this.build((Reader)reader, environment, (Properties)null);
   }
 
   public SqlSessionFactory build(Reader reader, Properties properties) {
       return this.build((Reader)reader, (String)null, properties);
   }
 
   public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
       SqlSessionFactory var5;
       try {
           XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
           var5 = this.build(parser.parse());
       } catch (Exception var14) {
           throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
       } finally {
           ErrorContext.instance().reset();
 
           try {
               reader.close();
           } catch (IOException var13) {
               ;
           }
 
       }
 
       return var5;
   }
 
   public SqlSessionFactory build(InputStream inputStream) {
       return this.build((InputStream)inputStream, (String)null, (Properties)null);
   }
 
   public SqlSessionFactory build(InputStream inputStream, String environment) {
       return this.build((InputStream)inputStream, environment, (Properties)null);
   }
 
   public SqlSessionFactory build(InputStream inputStream, Properties properties) {
       return this.build((InputStream)inputStream, (String)null, properties);
   }
 
   public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
       SqlSessionFactory var5;
       try {
           XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
           var5 = this.build(parser.parse());
       } catch (Exception var14) {
           throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
       } finally {
           ErrorContext.instance().reset();
 
           try {
               inputStream.close();
           } catch (IOException var13) {
               ;
           }
 
       }
 
       return var5;
   }
 
   public SqlSessionFactory build(Configuration config) {
       return new DefaultSqlSessionFactory(config);
   }
 

这里我们调用的build(reader)方法,最终会调用build(Reader reader, String environment, Properties properties),在这个方法里,会实例化一个XMLConfigBuilder对象,调用此对象的parse()方法来解析xml配置文件,源代码如下:

public Configuration parse() {
       if (this.parsed) {
           throw new BuilderException("Each XMLConfigBuilder can only be                 used once.");
       } else {
           this.parsed = true;
           this.parseConfiguration(this.parser.evalNode("/configuration"));
           return this.configuration;
       }
   }
private void parseConfiguration(XNode root) {
       try {
           this.propertiesElement(root.evalNode("properties"));
           Properties settings = this.settingsAsProperties(root.evalNode("settings"));
           this.loadCustomVfs(settings);
           this.typeAliasesElement(root.evalNode("typeAliases"));
           this.pluginElement(root.evalNode("plugins"));
           this.objectFactoryElement(root.evalNode("objectFactory"));
           this.objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
           this.reflectorFactoryElement(root.evalNode("reflectorFactory"));
           this.settingsElement(settings);
           this.environmentsElement(root.evalNode("environments"));
           this.databaseIdProviderElement(root.evalNode("databaseIdProvider"));
           this.typeHandlerElement(root.evalNode("typeHandlers"));
           this.mapperElement(root.evalNode("mappers"));
       } catch (Exception var3) {
           throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + var3, var3);
       }
   }

调用此方法后,会返回一个Configuration对象,此对象基本属性如下所示:

public class Configuration {
   protected Environment environment;
   protected boolean safeRowBoundsEnabled;
   protected boolean safeResultHandlerEnabled;
   protected boolean mapUnderscoreToCamelCase;
   protected boolean aggressiveLazyLoading;
   protected boolean multipleResultSetsEnabled;
   protected boolean useGeneratedKeys;
   protected boolean useColumnLabel;
   protected boolean cacheEnabled;
   protected boolean callSettersOnNulls;
   protected boolean useActualParamName;
   protected boolean returnInstanceForEmptyRow;
   protected String logPrefix;
   protected Class<? extends Log> logImpl;
   protected Class<? extends VFS> vfsImpl;
   protected LocalCacheScope localCacheScope;
   protected JdbcType jdbcTypeForNull;
   protected Set<String> lazyLoadTriggerMethods;
   protected Integer defaultStatementTimeout;
   protected Integer defaultFetchSize;
   protected ExecutorType defaultExecutorType;
   protected AutoMappingBehavior autoMappingBehavior;
   protected AutoMappingUnknownColumnBehavior      autoMappingUnknownColumnBehavior;
   protected Properties variables;
   protected ReflectorFactory reflectorFactory;
   protected ObjectFactory objectFactory;
   protected ObjectWrapperFactory objectWrapperFactory;
   protected boolean lazyLoadingEnabled;
   protected ProxyFactory proxyFactory;
   protected String databaseId;
   protected Class<?> configurationFactory;
   protected final MapperRegistry mapperRegistry;
   protected final InterceptorChain interceptorChain;
   protected final TypeHandlerRegistry typeHandlerRegistry;
   protected final TypeAliasRegistry typeAliasRegistry;
   protected final LanguageDriverRegistry languageRegistry;
   protected final Map<String, MappedStatement> mappedStatements;
   protected final Map<String, Cache> caches;
   protected final Map<String, ResultMap> resultMaps;
   protected final Map<String, ParameterMap> parameterMaps;
   protected final Map<String, KeyGenerator> keyGenerators;
   protected final Set<String> loadedResources;
   protected final Map<String, XNode> sqlFragments;
   protected final Collection<XMLStatementBuilder> incompleteStatements;
   protected final Collection<CacheRefResolver> incompleteCacheRefs;
   protected final Collection<ResultMapResolver> incompleteResultMaps;
   protected final Collection<MethodResolver> incompleteMethods;
   protected final Map<String, String> cacheRefMap;
}

最终,SqlSessionFactoryBuilder对象会调用build(Configuration config)方法,返回一个SqlSessionFactory对象,此方法源码如下:

public SqlSessionFactory build(Configuration config) {
       return new DefaultSqlSessionFactory(config);
}

DefaultSqlSessionFactory对象默认实现SqlSessionFactory接口,包含全局缓存的一个Configuration对象,源码大体如下:

public class DefaultSqlSessionFactory implements SqlSessionFactory {
   private final Configuration configuration;
 
   public DefaultSqlSessionFactory(Configuration configuration) {
       this.configuration = configuration;
   }
   、、、、
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值