spring 配置文件 sqlSessionFactory
1、sqlSessionFactory 继承关系
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IBe4IAYv-1646191461215)(素材/sqlSessionFactory继承关系.png)]
继承的接口:
-
InitializingBean:这个接口的作用是 spring 初始化的时候会执行实现了 InitializingBean 接口的
afterPropertiesSet()
方法;具体怎么执行暂时就不说了
-
ApplicationListener 接口作用:是在 spring 容器执行的各个阶段进行监听,SqlSessionFactoryBean 实现这个接口是为了容
器刷新的时候,更新 sqlSessionFactory;可以自己看下
onApplicationEvent()
方法实现; -
FactoryBean:实现这个接口表示这个类是一个工厂 bean,通常是为了给返回的类进行加工处理的,而且获取类返回的是通过
getObj 返回的;
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryBean.class);
private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = new PathMatchingResourcePatternResolver();
private static final MetadataReaderFactory METADATA_READER_FACTORY = new CachingMetadataReaderFactory();
private Resource configLocation;
private Configuration configuration;
private Resource[] mapperLocations;
private DataSource dataSource;
......
看这个类就从入口开始看,通过这个方法 afterPropertiesSet()
:
public void afterPropertiesSet() throws Exception {
//dataSource是必须要配置的
Assert.notNull(this.dataSource, "Property 'dataSource' is required");
Assert.notNull(this.sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
Assert.state(this.configuration == null && this.configLocation == null || this.configuration == null || this.configLocation == null, "Property 'configuration' and 'configLocation' can not specified with together");
//主要逻辑都在buildSqlSessionFactory方法,创建sqlSessionFactory,getObject就是返回的sqlSessionFactory
this.sqlSessionFactory = this.buildSqlSessionFactory();
}
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
this.afterPropertiesSet();
}
return this.sqlSessionFactory;
}
2、buildSqlSessionFactory 方法
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
XMLConfigBuilder xmlConfigBuilder = null;
Configuration targetConfiguration;
Optional var10000;
if (this.configuration != null) {
targetConfiguration = this.configuration;
if (targetConfiguration.getVariables() == null) {
targetConfiguration.setVariables(this.configurationProperties);
} else if (this.configurationProperties != null) {
targetConfiguration.getVariables().putAll(this.configurationProperties);
}
} else if (this.configLocation != null) {
xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), (String)null, this.configurationProperties);
targetConfiguration = xmlConfigBuilder.getConfiguration();
} else {
LOGGER.debug(() -> {
return "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration";
});
targetConfiguration = new Configuration();
var10000 = Optional.ofNullable(this.configurationProperties);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::setVariables);
}
var10000 = Optional.ofNullable(this.objectFactory);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::setObjectFactory);
var10000 = Optional.ofNullable(this.objectWrapperFactory);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::setObjectWrapperFactory);
var10000 = Optional.ofNullable(this.vfs);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::setVfsImpl);
Stream var24;
if (StringUtils.hasLength(this.typeAliasesPackage)) {
var24 = this.scanClasses(this.typeAliasesPackage, this.typeAliasesSuperType).stream().filter((clazz) -> {
return !clazz.isAnonymousClass();
}).filter((clazz) -> {
return !clazz.isInterface();
}).filter((clazz) -> {
return !clazz.isMemberClass();
});
TypeAliasRegistry var10001 = targetConfiguration.getTypeAliasRegistry();
Objects.requireNonNull(var10001);
var24.forEach(var10001::registerAlias);
}
if (!ObjectUtils.isEmpty(this.typeAliases)) {
Stream.of(this.typeAliases).forEach((typeAlias) -> {
targetConfiguration.getTypeAliasRegistry().registerAlias(typeAlias);
LOGGER.debug(() -> {
return "Registered type alias: '" + typeAlias + "'";
});
});
}
if (!ObjectUtils.isEmpty(this.plugins)) {
Stream.of(this.plugins).forEach((plugin) -> {
targetConfiguration.addInterceptor(plugin);
LOGGER.debug(() -> {
return "Registered plugin: '" + plugin + "'";
});
});
}
if (StringUtils.hasLength(this.typeHandlersPackage)) {
var24 = this.scanClasses(this.typeHandlersPackage, TypeHandler.class).stream().filter((clazz) -> {
return !clazz.isAnonymousClass();
}).filter((clazz) -> {
return !clazz.isInterface();
}).filter((clazz) -> {
return !Modifier.isAbstract(clazz.getModifiers());
});
TypeHandlerRegistry var25 = targetConfiguration.getTypeHandlerRegistry();
Objects.requireNonNull(var25);
var24.forEach(var25::register);
}
if (!ObjectUtils.isEmpty(this.typeHandlers)) {
Stream.of(this.typeHandlers).forEach((typeHandler) -> {
targetConfiguration.getTypeHandlerRegistry().register(typeHandler);
LOGGER.debug(() -> {
return "Registered type handler: '" + typeHandler + "'";
});
});
}
targetConfiguration.setDefaultEnumTypeHandler(this.defaultEnumTypeHandler);
if (!ObjectUtils.isEmpty(this.scriptingLanguageDrivers)) {
Stream.of(this.scriptingLanguageDrivers).forEach((languageDriver) -> {
targetConfiguration.getLanguageRegistry().register(languageDriver);
LOGGER.debug(() -> {
return "Registered scripting language driver: '" + languageDriver + "'";
});
});
}
var10000 = Optional.ofNullable(this.defaultScriptingLanguageDriver);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::setDefaultScriptingLanguage);
if (this.databaseIdProvider != null) {
try {
targetConfiguration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));
} catch (SQLException var23) {
throw new NestedIOException("Failed getting a databaseId", var23);
}
}
var10000 = Optional.ofNullable(this.cache);
Objects.requireNonNull(targetConfiguration);
var10000.ifPresent(targetConfiguration::addCache);
if (xmlConfigBuilder != null) {
try {
xmlConfigBuilder.parse();
LOGGER.debug(() -> {
return "Parsed configuration file: '" + this.configLocation + "'";
});
} catch (Exception var21) {
throw new NestedIOException("Failed to parse config resource: " + this.configLocation, var21);
} finally {
ErrorContext.instance().reset();
}
}
targetConfiguration.setEnvironment(new Environment(this.environment, (TransactionFactory)(this.transactionFactory == null ? new SpringManagedTransactionFactory() : this.transactionFactory), this.dataSource));
if (this.mapperLocations != null) {
if (this.mapperLocations.length == 0) {
LOGGER.warn(() -> {
return "Property 'mapperLocations' was specified but matching resources are not found.";
});
} else {
Resource[] var3 = this.mapperLocations;
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
Resource mapperLocation = var3[var5];
if (mapperLocation != null) {
try {
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments());
xmlMapperBuilder.parse();
} catch (Exception var19) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", var19);
} finally {
ErrorContext.instance().reset();
}
LOGGER.debug(() -> {
return "Parsed mapper file: '" + mapperLocation + "'";
});
}
}
}
} else {
LOGGER.debug(() -> {
return "Property 'mapperLocations' was not specified.";
});
}
return this.sqlSessionFactoryBuilder.build(targetConfiguration);
}
其实就是 xml 解析和赋值。