public SqlServerFlywayTestMigrationStrategy(DataSourceProperties dataSourceProps) { Pattern jdbcBaseUrlWithDbNamePattern = Pattern.compile(DB_URL_PATTERN); Matcher matcher = jdbcBaseUrlWithDbNamePattern.matcher(dataSourceProps.getUrl()); if(!matcher.matches()) { throw new IllegalArgumentException(dataSourceProps.getUrl() + " does not match " + DB_URL_PATTERN); } String jdbcBaseUrl = matcher.group("jdbcBaseUrl"); String databaseName = matcher.group("databaseName"); databaseExistsQuery = String.format("SELECT count(*) FROM sys.databases WHERE name='%s'", databaseName); createDatabaseQuery = String.format("CREATE DATABASE %s", databaseName); this.template = new JdbcTemplate(new SimpleDriverDataSource( getDriver(jdbcBaseUrl), jdbcBaseUrl, dataSourceProps.getUsername(), dataSourceProps.getPassword())); }
@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"); } } }
@Test public void dataSourceHealthIndicatorWithCustomValidationQuery() { this.context.register(PropertyPlaceholderAutoConfiguration.class, ManagementServerProperties.class, DataSourceProperties.class, DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class, HealthIndicatorAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.test.validation-query:SELECT from FOOBAR", "management.health.diskspace.enabled:false"); this.context.refresh(); Map<String, HealthIndicator> beans = this.context .getBeansOfType(HealthIndicator.class); assertThat(beans).hasSize(1); HealthIndicator healthIndicator = beans.values().iterator().next(); assertThat(healthIndicator.getClass()).isEqualTo(DataSourceHealthIndicator.class); DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator; assertThat(dataSourceHealthIndicator.getQuery()).isEqualTo("SELECT from FOOBAR"); }
@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; }
@Bean public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { log.debug("Configuring Heroku Datasource"); String herokuUrl = System.getenv("JDBC_DATABASE_URL"); if (herokuUrl != null) { HikariConfig config = new HikariConfig(); //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit()); } config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", herokuUrl); return new HikariDataSource(config); } else { throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL"); } }
@Test public void dataSourceHealthIndicatorWithCustomValidationQuery() { this.context.register(PropertyPlaceholderAutoConfiguration.class, ManagementServerProperties.class, DataSourceProperties.class, DataSourceConfig.class, DataSourcePoolMetadataProvidersConfiguration.class, HealthIndicatorAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.validation-query:SELECT from FOOBAR", "management.health.diskspace.enabled:false"); this.context.refresh(); Map<String, HealthIndicator> beans = this.context .getBeansOfType(HealthIndicator.class); assertEquals(1, beans.size()); HealthIndicator healthIndicator = beans.values().iterator().next(); assertEquals(DataSourceHealthIndicator.class, healthIndicator.getClass()); DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator; assertEquals("SELECT from FOOBAR", dataSourceHealthIndicator.getQuery()); }
@Bean public DataSource dataSource(DataSourceProperties dataSourceProperties, ApplicationProperties applicationProperties) { log.debug("Configuring Heroku Datasource"); String herokuUrl = System.getenv("JDBC_DATABASE_URL"); if (herokuUrl != null) { HikariConfig config = new HikariConfig(); //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", applicationProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", applicationProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", applicationProperties.getDatasource().getPrepStmtCacheSqlLimit()); } config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", herokuUrl); return new HikariDataSource(config); } else { throw new ApplicationContextException("Heroku database URL is not configured, you must set $JDBC_DATABASE_URL"); } }
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") public DataSource dataSource(DataSourceProperties dataSourceProperties, ApplicationProperties applicationProperties) { 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(environment.getActiveProfiles())); throw new ApplicationContextException("Database connection pool is not configured correctly"); } HikariConfig config = new HikariConfig(); config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", dataSourceProperties.getUrl()); config.addDataSourceProperty("user", dataSourceProperties.getUsername() != null ? dataSourceProperties.getUsername() : ""); config.addDataSourceProperty("password", dataSourceProperties.getPassword() != null ? dataSourceProperties.getPassword() : ""); if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } return new HikariDataSource(config); }
private XADataSource createXaDataSource(DataSourceProperties properties) throws ClassNotFoundException, LinkageError { String className = Optional .ofNullable(properties.getXa()) .map(Xa::getDataSourceClassName) .map(String::trim) .map(Strings::emptyToNull) .orElseGet(() -> DatabaseDriver .fromJdbcUrl(properties.determineUrl()) .getXaDataSourceClassName()); Assert.state(StringUtils.hasLength(className), "No XA DataSource class name specified or inferred"); XADataSource dataSource = createXaDataSourceInstance(className); bindXaProperties(dataSource, properties); return dataSource; }
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { 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"); } HikariConfig config = new HikariConfig(); config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", dataSourceProperties.getUrl()); if (dataSourceProperties.getUsername() != null) { config.addDataSourceProperty("user", dataSourceProperties.getUsername()); } else { config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user } if (dataSourceProperties.getPassword() != null) { config.addDataSourceProperty("password", dataSourceProperties.getPassword()); } else { config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password } if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } return new HikariDataSource(config); }
/** * 数据源配置对象 * Primary 表示默认的对象,Autowire可注入,不是默认的得明确名称注入 * @return */ @Bean @Primary @ConfigurationProperties("first.datasource") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); }
@Bean @ConditionalOnProperty(name = "spring.datasource1.url") @ConfigurationProperties(prefix = "spring.datasource1") public DataSourceInitializer dataSourceInitializer1(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 1); }
@Bean @ConditionalOnProperty(name = "spring.datasource2.url") @ConfigurationProperties(prefix = "spring.datasource2") public DataSourceInitializer dataSourceInitializer2(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 2); }
@Bean @ConditionalOnProperty(name = "spring.datasource3.url") @ConfigurationProperties(prefix = "spring.datasource3") public DataSourceInitializer dataSourceInitializer3(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 3); }
@Bean @ConditionalOnProperty(name = "spring.datasource4.url") @ConfigurationProperties(prefix = "spring.datasource4") public DataSourceInitializer dataSourceInitializer4(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 4); }
@Bean @ConditionalOnProperty(name = "spring.datasource5.url") @ConfigurationProperties(prefix = "spring.datasource5") public DataSourceInitializer dataSourceInitializer5(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 5); }
@Bean @ConditionalOnProperty(name = "spring.datasource6.url") @ConfigurationProperties(prefix = "spring.datasource6") public DataSourceInitializer dataSourceInitializer6(DataSourceProperties properties, ApplicationContext applicationContext) { return new DataSourceInitializer(properties, applicationContext, 6); }
protected org.apache.tomcat.jdbc.pool.DataSource createTomcatDataSource(DataSourceProperties properties) { org.apache.tomcat.jdbc.pool.DataSource dataSource = createDataSource( properties, org.apache.tomcat.jdbc.pool.DataSource.class); DatabaseDriver databaseDriver = DatabaseDriver .fromJdbcUrl(properties.determineUrl()); String validationQuery = databaseDriver.getValidationQuery(); if (validationQuery != null) { dataSource.setTestOnBorrow(true); dataSource.setValidationQuery(validationQuery); } return dataSource; }
@Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.tomcat") public org.apache.tomcat.jdbc.pool.DataSource dataSource( @Qualifier("dataSourceProperties") DataSourceProperties properties) { return createTomcatDataSource(properties); }
@Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.dbcp2") public org.apache.commons.dbcp2.BasicDataSource dataSource( @Qualifier("dataSourceProperties") DataSourceProperties properties) { return createDataSource(properties, org.apache.commons.dbcp2.BasicDataSource.class); }
@Bean @Primary public DataSourceProperties cloudSqlDataSourceProperties(DataSourceProperties properties, CloudSqlJdbcInfoProvider cloudSqlJdbcInfoProvider) { if (StringUtils.isEmpty(properties.getUsername())) { properties.setUsername("root"); LOGGER.warn("spring.datasource.username is not specified. Setting default username."); } if (StringUtils.isEmpty(properties.getDriverClassName())) { properties.setDriverClassName(cloudSqlJdbcInfoProvider.getJdbcDriverClass()); } else { LOGGER.warn( "spring.datasource.driver-class-name is specified. Not using generated Cloud SQL configuration"); } if (StringUtils.isEmpty(properties.getUrl())) { properties.setUrl(cloudSqlJdbcInfoProvider.getJdbcUrl()); } else { LOGGER.warn("spring.datasource.jdbc-url is specified. Not using generated Cloud SQL configuration"); } return properties; }
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") public DataSource dataSource(DataSourceProperties dataSourceProperties, LeagueProperties leagueProperties) { 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"); } HikariConfig config = new HikariConfig(); config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", dataSourceProperties.getUrl()); if (dataSourceProperties.getUsername() != null) { config.addDataSourceProperty("user", dataSourceProperties.getUsername()); } else { config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user } if (dataSourceProperties.getPassword() != null) { config.addDataSourceProperty("password", dataSourceProperties.getPassword()); } else { config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password } //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", leagueProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", leagueProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", leagueProperties.getDatasource().getPrepStmtCacheSqlLimit()); } if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } if (healthCheckRegistry != null) { config.setHealthCheckRegistry(healthCheckRegistry); } return new HikariDataSource(config); }
@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<% if (hibernateCache == 'hazelcast') { %>, CacheManager cacheManager<% } %>) { 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; } <%_ if (devDatabaseType == 'h2Disk' || devDatabaseType == 'h2Memory') { _%>
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { 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"); } HikariConfig config = new HikariConfig(); config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); config.addDataSourceProperty("url", dataSourceProperties.getUrl()); if (dataSourceProperties.getUsername() != null) { config.addDataSourceProperty("user", dataSourceProperties.getUsername()); } else { config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user } if (dataSourceProperties.getPassword() != null) { config.addDataSourceProperty("password", dataSourceProperties.getPassword()); } else { config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password } //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts()); config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize()); config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit()); } if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } return new HikariDataSource(config); }
@Test public void testConfigProps() throws Exception { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword()) .getForEntity("http://localhost:" + this.port + "/configprops", Map.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); @SuppressWarnings("unchecked") Map<String, Object> body = entity.getBody(); assertThat(body) .containsKey("spring.datasource-" + DataSourceProperties.class.getName()); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String[] dataSourceBeanNames = context.getBeanFactory() .getBeanNamesForType(DataSource.class); if (dataSourceBeanNames.length != 1) { return ConditionOutcome .noMatch("A single DataSource bean was not found in the context"); } if (context.getBeanFactory() .getBeanNamesForType(DataSourceProperties.class).length != 1) { return ConditionOutcome.noMatch( "A single DataSourceProperties bean was not found in the context"); } BeanDefinition dataSourceDefinition = context.getRegistry() .getBeanDefinition(dataSourceBeanNames[0]); if (dataSourceDefinition instanceof AnnotatedBeanDefinition && ((AnnotatedBeanDefinition) dataSourceDefinition) .getFactoryMethodMetadata() != null && ((AnnotatedBeanDefinition) dataSourceDefinition) .getFactoryMethodMetadata().getDeclaringClassName() .startsWith(DataSourceAutoConfiguration.class.getPackage() .getName() + ".DataSourceConfiguration$")) { return ConditionOutcome.match("Found auto-configured DataSource"); } return ConditionOutcome.noMatch("DataSource was not auto-configured"); }
@Bean public DataSource getDataSource(DataSourceProperties props) { // TODO: change to any middleware PGPoolingDataSource source = new PGPoolingDataSource(); source.setDataSourceName("eetds"); source.setServerName("localhost"); source.setDatabaseName(props.getName()); source.setUser(props.getUsername()); source.setPassword(props.getPassword()); source.setMaxConnections(10); // source.setUrl(""); return source; }
/** * Initializes the {@link DefaultTaskService}. * * @param dataSourceProperties the data source properties. * @param taskDefinitionRepository the {@link TaskDefinitionRepository} this service will * use for task CRUD operations. * @param taskExecutionRepository the repository this service will use for deployment IDs. * @param taskExplorer the explorer this service will use to lookup task executions * @param registry URI registry this service will use to look up app URIs. * @param resourceLoader the {@link ResourceLoader} that will resolve URIs to * {@link Resource}s. * @param taskLauncher the launcher this service will use to launch task apps. * @param metaDataResolver the metadata resolver * @param taskConfigurationProperties the properties used to define the behavior of tasks * @param deploymentIdRepository the repository that maps deployment keys to IDs * @param dataflowServerUri the data flow server URI */ public DefaultTaskService(DataSourceProperties dataSourceProperties, TaskDefinitionRepository taskDefinitionRepository, TaskExplorer taskExplorer, TaskRepository taskExecutionRepository, AppRegistryCommon registry, ResourceLoader resourceLoader, TaskLauncher taskLauncher, ApplicationConfigurationMetadataResolver metaDataResolver, TaskConfigurationProperties taskConfigurationProperties, DeploymentIdRepository deploymentIdRepository, String dataflowServerUri) { Assert.notNull(dataSourceProperties, "DataSourceProperties must not be null"); Assert.notNull(taskDefinitionRepository, "TaskDefinitionRepository must not be null"); Assert.notNull(taskExecutionRepository, "TaskExecutionRepository must not be null"); Assert.notNull(taskExplorer, "TaskExplorer must not be null"); Assert.notNull(registry, "UriRegistry must not be null"); Assert.notNull(resourceLoader, "ResourceLoader must not be null"); Assert.notNull(taskLauncher, "TaskLauncher must not be null"); Assert.notNull(metaDataResolver, "metaDataResolver must not be null"); Assert.notNull(taskConfigurationProperties, "taskConfigurationProperties must not be null"); Assert.notNull(deploymentIdRepository, "deploymentIdRepository must not be null"); this.dataSourceProperties = dataSourceProperties; this.taskDefinitionRepository = taskDefinitionRepository; this.taskExecutionRepository = taskExecutionRepository; this.taskExplorer = taskExplorer; this.registry = registry; this.taskLauncher = taskLauncher; this.resourceLoader = resourceLoader; this.whitelistProperties = new WhitelistProperties(metaDataResolver); this.taskConfigurationProperties = taskConfigurationProperties; this.deploymentIdRepository = deploymentIdRepository; this.dataflowServerUri = dataflowServerUri; }