1 DataSourceAutoConfiguration 功能概况
- 初始化
DataSourceProperties
配置文件
- 初始化数据源
- 执行
sql 文件
- 为数据源注册一个
DataSourcePoolMetadataProvider
实例
2 源码分析
@Configuration
@ConditionalOnClass({
DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({
DataSourcePoolMetadataProvidersConfiguration.class,
DataSourceInitializationConfiguration.class })
public class DataSourceAutoConfiguration {
@Configuration
@Conditional(EmbeddedDatabaseCondition.class)
@ConditionalOnMissingBean({
DataSource.class, XADataSource.class })
@Import(EmbeddedDataSourceConfiguration.class)
protected static class EmbeddedDatabaseConfiguration {
}
@Configuration
@Conditional(PooledDataSourceCondition.class)
@ConditionalOnMissingBean({
DataSource.class, XADataSource.class })
@Import({
DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class,
DataSourceJmxConfiguration.class })
protected static class PooledDataSourceConfiguration {
}
static class PooledDataSourceCondition extends AnyNestedCondition {
}
static class EmbeddedDatabaseCondition extends SpringBootCondition {
}
}
2.1 初始化 DataSourceProperties 配置文件
- 如果设置的不是内置数据库的话:
1)必须配置的有:url,username,password
2)数据库名不是必须的
3)driverClassName 不是必须的:可以从 url 中推导出
4)type 不是必须的:可以从上下文中推导出
- 如果设置的是内置数据库的话:
1)必须配置的有:引入内置数据库依赖,如:H2
2)其它所有的都可以不配置(有默认的配置),如果随意配置,可能产生冲突
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
private String name;
private boolean generateUniqueName;
private String uniqueName;
private Class<? extends DataSource> type;
private String driverClassName;
private String url;
private String username;
private String password;
private String jndiName;
private DataSourceInitializationMode initializationMode = DataSourceInitializationMode.EMBEDDED;
private String platform = "all";
private List<String> schema;
private String schemaUsername;
private String schemaPassword;
private List<String> data;
private String dataUsername;
private String dataPassword;