SpringBoot 自动数据源配置分析
前言
通过分析源码来配置我们自己的数据源,不在百度复制粘贴。
说明:文章内的源码都是局部的。开发这东西需要动手操作。
application.properties方式配置数据源
这可能是初学者或第一次使用SpringBoot的最常见的方式了。
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.url=jdbc:mysql://localhost:3306/test_db?characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
为什么这样配置就可以呢?
- 首选我们要了解SpringBoot的数据源自动配置
- DataSourceBuilder 构建器
源码之路开始😊
数据源自动配置
类
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
代码
static class PooledDataSourceAvailableCondition extends SpringBootCondition {
PooledDataSourceAvailableCondition() {
}
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Builder message = ConditionMessage.forCondition("PooledDataSource", new Object[0]);
return DataSourceBuilder.findType(context.getClassLoader()) != null ? ConditionOutcome.match(message.foundExactly("supported DataSource")) : ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll());
}
}
在这里我发现了DataSourceBuilder
使用
1、DataSourceAutoConfiguration 类在启动的时候会通过SpringBoot自动配置管理器自动执行配置。
2、如果后期项目配置多数据源或者自己的数据源强烈建议过滤掉数据源自动配置。不然会出现多数据源配置默认数据源(@Primary)时候冲突问题。
DataSourceBuilder 构建器
类
org.springframework.boot.jdbc.DataSourceBuilder
代码‘
private static final String[] DATA_SOURCE_TYPE_NAMES = new String[]{"com.zaxxer.hikari.HikariDataSource", "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"};
private Class<? extends DataSource> type;
private ClassLoader classLoader;
private Map<String, String> properties = new HashMap();
1、代码中看见支持三种数据源,SpringBoot默认支持的是HikariDataSource
2、type 是切换数据源配置。实际开发中基本用不到,因为我们不会这么配置数据源。
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
3、properties参数:数据源的全部属性以Key Value形式存储。执行build()方法的时候会把值赋值给实际数据源HikariDataSource
public T build() {
Class<? extends DataSource> type = this.getType();
DataSource result = (DataSource)BeanUtils.instantiateClass(type);
this.maybeGetDriverClassName();
this.bind(result);
return result;
}
private void bind(DataSource result) {
ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
aliases.addAliases("url", new String[]{"jdbc-url"});
aliases.addAliases("username", new String[]{"user"});
Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(aliases)});
binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
扩展
1、通过application配置:driver-class-name 实际属性值:driverClassName