Mybatis创建SqlSessionFactory对象初始化过程
String config = "mybatis/config.xml";
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
本文主要分析SqlSessionFactory初始化过程:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
第一步: 执行build(inputStream)
方法,方法里创建了XMLConfigBuilder
类;
///1、SqlSessionFactory类的build 方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
SqlSessionFactory var5;
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// 执行parser.parse()方法
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;
}
第二步: 执行XMLConfigBuilder
的parse()
方法,parse()
方法里最终调用parseConfiguration
方法,找到Mybatis的config.xml中的configuration节点;
public Configuration parse() {
if (this.parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
} else {
this.parsed = true;
// 2、执行parseConfiguration 方法,找到Mybatis的config.xml中的configuration节点
this.parseConfiguration(this.parser.evalNode("/configuration"));
return this.configuration;
}
}
第三步: 执行XMLConfigBuilder
的parse()
方法,parse()
方法里最终调用parseConfiguration
方法,parseConfiguration
方法最终解析config.xml文件中的各个节点;
private void parseConfiguration(XNode root) {
try {
this.propertiesElement(root.evalNode("properties"));
Properties settings = this.settingsAsProperties(root.evalNode("settings"));
this.loadCustomVfs(settings);
this.loadCustomLogImpl(settings);
this.typeAliasesElement(root.evalNode("typeAliases"));
this.pluginElement(root.evalNode("plugins"));
this.objectFactoryElement(root.evalNode("objectFactory"));
this.objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));