1.JDBC
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
spring:
datasource:
username: root
password: vinllor
url: jdbc:mysql://127.0.0.1:3306/springboot01
driver
默认使用class com.zaxxer.hikari.HikariDataSource作为数据源
数据源相关配置
@ConfigurationProperties(
prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
自动配置原理
/org/springframework/boot/autoconfigure/jdbc
1.参考DataSourceConfiguration默认使用HikariDataSource ,
使用自定义的spring.datasource.type指定自定义的数据源类型
- springboot 默认支持com.zaxxer.hikari.HikariDataSource"
org.apache.tomcat.jdbc.pool.DataSource org.apache.commons.dbcp2.BasicDataSource - 自定义数据源
@Configuration
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
@Bean
public DataSource dataSource(DataSourceProperties properties) {
// properties,利用反射创建type的数据源,并绑定属性
return properties.initializeDataSourceBuilder().build();
}
}
- DataSourceInitializer:ApplicationListener;
作用:- runSchemaScripts: 运行建表语句
- runDataScripts:运行插入数据的sql语句;
默认将文件命名为:schema-.sql,data-.sql