下面列出了怎么用org.springframework.boot.autoconfigure.jdbc.DataSourceProperties的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
ClassUtils.forName("com.alibaba.druid.pool.DruidDataSource",this.getClass().getClassLoader());
} catch (ClassNotFoundException e) {
return;
}
applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DataSourceProperties) {
DataSourceProperties dataSourceProperties = (DataSourceProperties)bean;
DruidAndMybatisApplicationContextInitializer.this.rewirteDataSourceProperties(dataSourceProperties);
} else if (bean instanceof MybatisProperties) {
MybatisProperties mybatisProperties = (MybatisProperties)bean;
DruidAndMybatisApplicationContextInitializer.this.rewriteMybatisProperties(mybatisProperties);
}
return bean;
}
});
}
@Bean
public HikariDataSource dataSource(DataSourceProperties properties) {
HikariDataSource hikariDataSource = (HikariDataSource) properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
hikariDataSource.setConnectionTimeout(DB_CONN_TIMEOUT);
hikariDataSource.setMaximumPoolSize(DB_MAX_POOL_SIZE);
hikariDataSource.setMaxLifetime(DB_MAX_LIFE_TIME);
hikariDataSource.setAutoCommit(DB_AUTOCOMMIT);
hikariDataSource.setConnectionTestQuery("SELECT 1");
hikariDataSource.addDataSourceProperty("cachePrepStmts", DB_CACHE_PREP_STMTS);
hikariDataSource.addDataSourceProperty("prepStmtCacheSize", DB_PREP_STMT_CACHE_SIZE);
hikariDataSource.addDataSourceProperty("prepStmtCacheSqlLimit", DB_PREP_STMT_CACHE_SQL_LIMIT);
hikariDataSource.addDataSourceProperty("useServerPrepStmts", DB_USE_SERVER_PREP_STMTS);
hikariDataSource.addDataSourceProperty("useLocalSessionState", DB_USE_LOCAL_SESSION_STATE);
hikariDataSource.addDataSourceProperty("rewriteBatchedStatements", DB_REWRITE_BATCHED_STATEMENTS);
hikariDataSource.addDataSourceProperty("cacheResultSetMetadata", DB_CACHE_RESULT_SET_METADATA);
hikariDataSource.addDataSourceProperty("cacheServerConfiguration", DB_CACHE_SERVER_CONFIGURATION);
hikariDataSource.addDataSourceProperty("elideSetAutoCommits", DB_ELIDE_SET_AUTO_COMMITS);
hikariDataSource.addDataSourceProperty("maintainTimeStats", DB_MAINTAIN_TIME_STATS);
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
" cannot start. Please check your Spring profile, current profiles are: {}",
Arrays.toString(env.getActiveProfiles()));
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.driverClassName(dataSourceProperties.getDriverClassName())
.url(dataSourceProperties.getUrl())
.username(dataSourceProperties.getUsername())
.password(dataSourceProperties.getPassword())
.build();
if (metricRegistry != null) {
hikariDataSource.setMetricRegistry(metricRegistry);
}
return hikariDataSource;
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public DataSource dataSource(DataSourceProperties dataSourceProperties<% if (hibernateCache == 'hazelcast') { %>, CacheManager cacheManager<% } %>) {
log.debug("Configuring Heroku Datasource");
String herokuUrl = System.getenv("JDBC_DATABASE_URL");
if (herokuUrl != null) {
return DataSourceBuilder
.create(dataSourceProperties.getClassLoader())
.type(HikariDataSource.class)
.url(herokuUrl)
.build();
} else {
throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL");
}
}
}
@Bean
public DataSource configurationDataSource(@Autowired DataSourceProperties configDataSourceProperties) {
String url = configDataSourceProperties.getUrl();
// A simple inspection is done on the JDBC URL to deduce whether to create an in-memory
// in-process database, start a file-based externally visible database or connect to
// an external database.
if (url.contains("hsql")) {
String username = configDataSourceProperties.getUsername();
String password = configDataSourceProperties.getPassword();
return HsqlDatabaseBuilder.builder()
.url(url)
.username(username)
.password(password)
.script(new ClassPathResource("sql/config-schema-hsqldb.sql"))
.build().toDataSource();
} else {
return configDataSourceProperties.initializeDataSourceBuilder().build();
}
}
@Bean
@ConfigurationProperties("c2mon.server.history.jdbc")
public DataSource historyDataSource(@Autowired DataSourceProperties historyDataSourceProperties) {
String url = historyDataSourceProperties.getUrl();
if (url.contains("hsql")) {
String username = historyDataSourceProperties.getUsername();
String password = historyDataSourceProperties.getPassword();
return HsqlDatabaseBuilder.builder()
.url(url)
.username(username)
.password(password)
.script(new ClassPathResource("sql/history-schema-hsqldb.sql")).build()
.toDataSource();
} else {
return historyDataSourceProperties.initializeDataSourceBuilder().build();
}
}
@Bean
public DataSource cacheDataSource(@Autowired DataSourceProperties cacheDataSourceProperties) {
String url = cacheDataSourceProperties.getUrl();
// A simple inspection is done on the JDBC URL to deduce whether to create an in-memory
// in-process database, start a file-based externally visible database or connect to
// an external database.
if (url.contains("hsql")) {
String username = cacheDataSourceProperties.getUsername();
String password = cacheDataSourceProperties.getPassword();
return HsqlDatabaseBuilder.builder().url(url).username(username).password(password)
.script(new ClassPathResource("sql/cache-schema-hsqldb.sql")).build().toDataSource();
} else {
return cacheDataSourceProperties.initializeDataSourceBuilder().build();
}
}
@Bean
@Primary
public DataSourceProperties dataSourceProperties() {
DataSourceProperties properties = new DataSourceProperties();
properties.setInitialize(false);
// dbName.serviceName example: user-db.mysql (we must )
final String serviceId = environment.getProperty(MYSQL_SERVICE_ID);
if (discoveryClient != null && serviceId != null) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
if (!instances.isEmpty()) {
properties.setUrl(getJdbcUrl(instances, fetchDBName(serviceId)));
} else {
LOGGER.warn("there is no services with id {} in service discovery", serviceId);
}
}
return properties;
}
@Test
public void testDatabasePropUpdate() {
TaskDefinition taskDefinition = new TaskDefinition("testTask", "testApp");
DataSourceProperties dataSourceProperties = new DataSourceProperties();
dataSourceProperties.setUsername("myUser");
dataSourceProperties.setDriverClassName("myDriver");
dataSourceProperties.setPassword("myPassword");
dataSourceProperties.setUrl("myUrl");
TaskDefinition definition = TaskServiceUtils.updateTaskProperties(
taskDefinition,
dataSourceProperties);
assertThat(definition.getProperties().size()).isEqualTo(5);
assertThat(definition.getProperties().get("spring.datasource.url")).isEqualTo("myUrl");
assertThat(definition.getProperties().get("spring.datasource.driverClassName")).isEqualTo("myDriver");
assertThat(definition.getProperties().get("spring.datasource.username")).isEqualTo("myUser");
assertThat(definition.getProperties().get("spring.datasource.password")).isEqualTo("myPassword");
}
@Test
public void createSpringLiquibaseFromLiquibaseProperties() {
DataSource liquibaseDatasource = null;
LiquibaseProperties liquibaseProperties = new LiquibaseProperties();
liquibaseProperties.setUrl("jdbc:h2:mem:liquibase");
liquibaseProperties.setUser("sa");
DataSource normalDataSource = null;
DataSourceProperties dataSourceProperties = new DataSourceProperties();
dataSourceProperties.setPassword("password");
SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDatasource, liquibaseProperties, normalDataSource, dataSourceProperties);
assertThat(liquibase)
.asInstanceOf(type(DataSourceClosingSpringLiquibase.class))
.extracting(SpringLiquibase::getDataSource)
.asInstanceOf(type(HikariDataSource.class))
.hasFieldOrPropertyWithValue("jdbcUrl", "jdbc:h2:mem:liquibase")
.hasFieldOrPropertyWithValue("username", "sa")
.hasFieldOrPropertyWithValue("password", "password");
}
@Test
public void createAsyncSpringLiquibaseFromLiquibaseProperties() {
DataSource liquibaseDatasource = null;
LiquibaseProperties liquibaseProperties = new LiquibaseProperties();
liquibaseProperties.setUrl("jdbc:h2:mem:liquibase");
liquibaseProperties.setUser("sa");
DataSource normalDataSource = null;
DataSourceProperties dataSourceProperties = new DataSourceProperties();
dataSourceProperties.setPassword("password");
AsyncSpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(null, null, liquibaseDatasource, liquibaseProperties, normalDataSource, dataSourceProperties);
assertThat(liquibase.getDataSource())
.asInstanceOf(type(HikariDataSource.class))
.hasFieldOrPropertyWithValue("jdbcUrl", "jdbc:h2:mem:liquibase")
.hasFieldOrPropertyWithValue("username", "sa")
.hasFieldOrPropertyWithValue("password", "password");
}
/**
* Updates the task definition with the datasource properties.
* @param taskDefinition the {@link TaskDefinition} to be updated.
* @param dataSourceProperties the dataSource properties used by SCDF.
* @return the updated {@link TaskDefinition}
*/
public static TaskDefinition updateTaskProperties(TaskDefinition taskDefinition,
DataSourceProperties dataSourceProperties) {
Assert.notNull(taskDefinition, "taskDefinition must not be null");
Assert.notNull(dataSourceProperties, "dataSourceProperties must not be null");
TaskDefinition.TaskDefinitionBuilder builder = TaskDefinition.TaskDefinitionBuilder.from(taskDefinition);
builder.setProperty("spring.datasource.url", dataSourceProperties.getUrl());
builder.setProperty("spring.datasource.username", dataSourceProperties.getUsername());
// password may be empty
if (StringUtils.hasText(dataSourceProperties.getPassword())) {
builder.setProperty("spring.datasource.password", dataSourceProperties.getPassword());
}
builder.setProperty("spring.datasource.driverClassName", dataSourceProperties.getDriverClassName());
builder.setTaskName(taskDefinition.getTaskName());
builder.setDslText(taskDefinition.getDslText());
return builder.build();
}
/**
* Initializes the {@link DefaultTaskExecutionInfoService}.
*
* @param dataSourceProperties the data source properties.
* @param appRegistryService URI registry this service will use to look up app URIs.
* @param taskExplorer the explorer this service will use to lookup task executions
* @param taskDefinitionRepository the {@link TaskDefinitionRepository} this service will
* use for task CRUD operations.
* @param taskConfigurationProperties the properties used to define the behavior of tasks
* @param launcherRepository the launcher repository
* @param taskPlatforms the task platforms
*/
public DefaultTaskExecutionInfoService(DataSourceProperties dataSourceProperties,
AppRegistryService appRegistryService,
TaskExplorer taskExplorer,
TaskDefinitionRepository taskDefinitionRepository,
TaskConfigurationProperties taskConfigurationProperties,
LauncherRepository launcherRepository,
List<TaskPlatform> taskPlatforms) {
Assert.notNull(dataSourceProperties, "DataSourceProperties must not be null");
Assert.notNull(appRegistryService, "AppRegistryService must not be null");
Assert.notNull(taskDefinitionRepository, "TaskDefinitionRepository must not be null");
Assert.notNull(taskExplorer, "TaskExplorer must not be null");
Assert.notNull(taskConfigurationProperties, "taskConfigurationProperties must not be null");
Assert.notNull(launcherRepository, "launcherRepository must not be null");
Assert.notEmpty(taskPlatforms, "taskPlatform must not be empty or null");
this.dataSourceProperties = dataSourceProperties;
this.appRegistryService = appRegistryService;
this.taskExplorer = taskExplorer;
this.taskDefinitionRepository = taskDefinitionRepository;
this.taskConfigurationProperties = taskConfigurationProperties;
this.launcherRepository = launcherRepository;
this.taskPlatforms = taskPlatforms;
}
private void rewirteDataSourceProperties(DataSourceProperties dataSourceProperties) {
if (dataSourceProperties.getType() == null) {
dataSourceProperties.setType(com.alibaba.druid.pool.DruidDataSource.class);
}
if (dataSourceProperties.getPlatform().equals("all")) {
dataSourceProperties.setPlatform("mysql");
}
}
@Override
public Object postProcessAfterInitialization(@NonNull final Object bean, final String beanName) throws BeansException {
if (bean instanceof DataSourceProperties) {
this.init((DataSourceProperties) bean);
}
return bean;
}
@SneakyThrows
protected void init(final DataSourceProperties properties) {
// If jdbcUrl in the configuration file specifies the soul database, it is removed,
// because the soul database does not need to be specified when executing the SQL file,
// otherwise the soul database will be disconnected when the soul database does not exist
String jdbcUrl = StringUtils.replace(properties.getUrl(), "/soul?", "?");
Connection connection = DriverManager.getConnection(jdbcUrl, properties.getUsername(), properties.getPassword());
this.execute(connection);
}
@Bean
@Primary
@ConditionalOnMissingBean(value = DruidDataSourceInitializer.class, name = "dataSourceInitializer")
public DruidDataSourceInitializer dataSourceInitializer(DataSourceProperties properties,
ApplicationContext applicationContext) {
return new DruidDataSourceInitializer(properties, applicationContext);
}
/**
* 数据源配置对象
* Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入
* @return
*/
@Bean
@Primary
@ConfigurationProperties("first.datasource")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties(prefix = "datasource")
public DataSourceProperties dataSourceProperties() {
DataSourceProperties props = new DataSourceProperties();
props.setUrl(
"jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS "
+ schemaName);
return props;
}
@Bean
@Primary
@ConfigurationProperties(prefix = "datasource")
public DataSourceProperties dataSourceProperties() {
DataSourceProperties props = new DataSourceProperties();
props.setUrl(
"jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS "
+ schemaName);
return props;
}
@Bean
@Primary
@ConfigurationProperties(prefix = "datasource")
public DataSourceProperties dataSourceProperties() {
DataSourceProperties props = new DataSourceProperties();
props.setUrl(
"jdbc:h2:mem:taskana;IGNORECASE=TRUE;LOCK_MODE=0;INIT=CREATE SCHEMA IF NOT EXISTS "
+ schemaName);
return props;
}
public LogDbProperties(@Autowired(required = false) DataSourceProperties dataSourceProperties) {
if (Objects.isNull(dataSourceProperties) ||
Objects.isNull(dataSourceProperties.getDriverClassName()) ||
Objects.isNull(dataSourceProperties.getUrl())) {
log.info("TxLogger used user's config.");
return;
}
this.setDriverClassName(dataSourceProperties.getDriverClassName());
this.setJdbcUrl(dataSourceProperties.getUrl());
this.setUsername(dataSourceProperties.getUsername());
this.setPassword(dataSourceProperties.getPassword());
}
/**
* 初始化数据源
* @param id 数据源id
* @return 数据源
*/
private HikariDataSource initDatasource(Long id) {
HikariDataSource dataSource = new HikariDataSource();
// 判断是否是默认数据源
if (DatasourceHolder.DEFAULT_ID.equals(id)) {
// 默认数据源根据 application.yml 配置的生成
DataSourceProperties properties = SpringUtil.getBean(DataSourceProperties.class);
dataSource.setJdbcUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
} else {
// 不是默认数据源,通过缓存获取对应id的数据源的配置
DatasourceConfig datasourceConfig = DatasourceConfigCache.INSTANCE.getConfig(id);
if (datasourceConfig == null) {
throw new RuntimeException("无此数据源");
}
dataSource.setJdbcUrl(datasourceConfig.buildJdbcUrl());
dataSource.setUsername(datasourceConfig.getUsername());
dataSource.setPassword(datasourceConfig.getPassword());
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
}
// 将创建的数据源添加到数据源管理器中,绑定当前线程
DatasourceHolder.INSTANCE.addDatasource(id, dataSource);
return dataSource;
}
@Bean
public TaskExecutionInfoService taskDefinitionRetriever(AppRegistryService registry,
TaskExplorer taskExplorer, TaskDefinitionRepository taskDefinitionRepository,
TaskConfigurationProperties taskConfigurationProperties, LauncherRepository launcherRepository,
List<TaskPlatform> platforms) {
return new DefaultTaskExecutionInfoService(new DataSourceProperties(),
registry, taskExplorer, taskDefinitionRepository,
taskConfigurationProperties, launcherRepository, platforms);
}
@Bean
@ConfigurationProperties("spring.datasource")
@LiquibaseDataSource
public DataSource dataSource(DataSourceProperties properties) {
return new SimpleDriverDataSource(new org.postgresql.Driver(), properties.getUrl(),
properties.getDataUsername(), properties.getDataPassword());
}
@Bean
@ConfigurationProperties("spring.datasource")
@LiquibaseDataSource
public DataSource dataSource(DataSourceProperties properties) {
return new SimpleDriverDataSource(new org.postgresql.Driver(), properties.getUrl(),
properties.getDataUsername(), properties.getDataPassword());
}
@Test
public void testNoJdbc() {
this.contextRunner.withPropertyValues(
"spring.cloud.gcp.sql.instanceConnectionName=tubular-bells:singapore:test-instance")
.withClassLoader(
new FilteredClassLoader(EmbeddedDatabaseType.class, DataSource.class))
.run((context) -> {
assertThat(context.getBeanNamesForType(DataSource.class)).isEmpty();
assertThat(context.getBeanNamesForType(DataSourceProperties.class)).isEmpty();
assertThat(context.getBeanNamesForType(GcpCloudSqlProperties.class)).isEmpty();
assertThat(context.getBeanNamesForType(CloudSqlJdbcInfoProvider.class)).isEmpty();
});
}
@Bean
public DataSource datasource(DataSourceProperties dataSourceProperties) {
HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
dataSource.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 2);
return dataSource;
}
@Primary
@Bean(name = "userDataSource")
@ConfigurationProperties("user.datasource.configuration")
public DataSource dataSource(@Qualifier("userDataSourceProperties") DataSourceProperties userDataSourceProperties) {
return userDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}