Mybatis源碼解析之初始化分析
一、 Mybatis配置文件
configuation是mybatis配置文件的根節(jié)點。
configuration 配置 -properties 屬性 -settings 設(shè)置 -typeAliases 類型別名 -typeHandlers 類型處理器 -objectFactory 對象工廠 -plugins 插件 -environments 環(huán)境 -environment 環(huán)境變量 -transactionManager 事務(wù)管理器 -dataSource 數(shù)據(jù)源 -databaseIdProvider 數(shù)據(jù)庫廠商標識 -mappers 映射器
本文主要講解源碼,不對配置文件展開
二、配置文件解析過程
1. 初始化demo
下文代碼是mybatis通過解析xml配置文件進行初始化的一個簡單demo,后續(xù)我們將根據(jù)這個demo追蹤mybatis源碼的處理過程。
InputStream inputStream = Resources.getResourceAsStream("mybatis-coonfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
2. SqlSessionFactoryBuilder#build(InputStream, String. Properties)
SqlSessionFactoryBuilder的build(inputStream)方法通過調(diào)用同名的重載方法SqlSessionFactoryBuilder#build(InputStream, String. Properties)來生成需要的SqlSessionFacotry。
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}首先,通過XmlConfigBuilder解析配置文件,并得到configuration類對象。 然后根據(jù)configuration作為參數(shù)調(diào)用build得到所需的SqlSessionFactory,可以看到最終得到的SqlSessionFactory類型是DefaultSqlSessionFactory。
3. XMLConfigBuilder#parse()
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}可以看到,XMLConfigBuilder對xml配置文件中對configuration的子節(jié)點進行逐個解析。 以typeAliases為例,遍歷typeAliases的子節(jié)點,根據(jù)配置情況將其加入到configuration對象中對應(yīng)的typeAliasRegistry屬性,其它節(jié)點的解析也類似。
private void typeAliasesElement(XNode parent) {
if (parent != null) {
for (XNode child : parent.getChildren()) {
if ("package".equals(child.getName())) {
String typeAliasPackage = child.getStringAttribute("name");
configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
} else {
String alias = child.getStringAttribute("alias");
String type = child.getStringAttribute("type");
try {
Class<?> clazz = Resources.classForName(type);
if (alias == null) {
typeAliasRegistry.registerAlias(clazz);
} else {
typeAliasRegistry.registerAlias(alias, clazz);
}
} catch (ClassNotFoundException e) {
throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
}
}
}
}
}4. DefaultSqlSessionFactory#openSession()
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}DefaultSqlSessionFactory#openSession()最終通過DefaultSqlSessionFactory#openSessionFromDataSource(ExecutorType, TransactionLevel, boolean)試下,可以看到最后獲得的SqlSession類型是DefaultSqlSession,其中executor類型是SimpleExecutor。
到此這篇關(guān)于Mybatis源碼解析之初始化分析的文章就介紹到這了,更多相關(guān)Mybatis初始化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java線程編程中Thread類的基礎(chǔ)學(xué)習(xí)教程
這篇文章主要介紹了Java線程編程中Thread類的基礎(chǔ)學(xué)習(xí)教程,Thread類包含諸多操作線程的方法,非常重要,需要的朋友可以參考下2015-12-12
springboot結(jié)合maven配置不同環(huán)境的profile方式
這篇文章主要介紹了springboot結(jié)合maven配置不同環(huán)境的profile方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
springboot編程式事務(wù)TransactionTemplate的使用說明
這篇文章主要介紹了springboot編程式事務(wù)TransactionTemplate的使用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringCloud Gateway動態(tài)轉(zhuǎn)發(fā)后端服務(wù)實現(xiàn)過程講解
這篇文章主要介紹了SpringCloud Gateway動態(tài)轉(zhuǎn)發(fā)后端服務(wù)實現(xiàn)過程,簡單的路由轉(zhuǎn)發(fā)可以通過SpringCloudGateway的配置文件實現(xiàn),在一些業(yè)務(wù)場景種,會需要動態(tài)替換路由配置中的后端服務(wù)地址,單純靠配置文件無法滿足這種需求2023-03-03

