依赖
1 2 3 4 5 6
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>2.6.13</version> <scope>compile</scope> </dependency>
|
spring-boot-starter-jdbc
中 引入了
1 2 3 4 5 6
| <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>4.0.3</version> <scope>compile</scope> </dependency>
|
入口
1 2 3 4 5 6 7 8 9 10 11
| org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
@Configuration(proxyBeanMethods = false) @Conditional(PooledDataSourceCondition.class) @ConditionalOnMissingBean({ DataSource.class, XADataSource.class }) @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class, DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class, DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class }) protected static class PooledDataSourceConfiguration {
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration
@Configuration(proxyBeanMethods = false) @ConditionalOnClass(HikariDataSource.class) @ConditionalOnMissingBean(DataSource.class) @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource", matchIfMissing = true) static class Hikari {
@Bean @ConfigurationProperties(prefix = "spring.datasource.hikari") HikariDataSource dataSource(DataSourceProperties properties) { HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class); if (StringUtils.hasText(properties.getName())) { dataSource.setPoolName(properties.getName()); } return dataSource; }
}
@SuppressWarnings("unchecked") protected static <T> T createDataSource(DataSourceProperties properties, Class<? extends DataSource> type) { return (T) properties.initializeDataSourceBuilder().type(type).build(); }
|
自定义
1 2 3 4 5 6 7
| spring: datasource: one: driver-class-name: com.mysql.cj.jdbc.Driver password: YdpQwIoy8E0dFWH7 url: jdbc:mysql://10.10.10.206:3306/coredb?useOldAliasMetadataBehavior=true username: coreuser
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Configuration public class DataSourceConfig {
@Bean(name = "oneDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.one") public DataSourceProperties oneDataSourceProperties() { return new DataSourceProperties(); }
@Bean(name = "dsOne") DataSource dsOne(@Qualifier("oneDataSourceProperties") DataSourceProperties properties) { return properties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); }
@Bean(name = "jdbcTemplateOne") JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dsOne) { return new JdbcTemplate(dsOne); } }
|
数据源参考
- spring-boot-autoconfigure
- spring-boot-starter-jdbc
- sharding-jdbc-spring-boot-starter
- dynamic-datasource-spring-boot-starter