org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder Java Examples

The following examples show how to use org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DruidDataSourceInitializer.java    From druid-spring-boot with Apache License 2.0 7 votes vote down vote up
private void runScripts(DataSource dataSource, List<Resource> resources, String username, String password) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(this.properties.isContinueOnError());
    populator.setSeparator(this.properties.getSeparator());
    if (this.properties.getSqlScriptEncoding() != null) {
        populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name());
    }
    for (Resource resource : resources) {
        populator.addScript(resource);
    }
    if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
        dataSource = DataSourceBuilder.create(this.properties.getClassLoader())
                .driverClassName(this.properties.determineDriverClassName())
                .url(this.properties.determineUrl())
                .username(username)
                .password(password)
                .build();
    }
    DatabasePopulatorUtils.execute(populator, dataSource);
}
 
Example #2
Source File: DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: DatabaseConfiguration.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: DatabaseConfiguration.java    From OpenIoE with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: DatabaseConfiguration.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: SqlRewriterConfiguration.java    From calcite-sql-rewriter with Apache License 2.0 6 votes vote down vote up
@Bean
public JdbcTemplate postgresJdbcTemplate(
		@Value("${postgres.jdbcUrl}") String postgresJdbcUrl,
		@Value("${postgres.jdbcDriver}") String postgresJdbcDriver,
		@Value("${postgres.jdbcUser}") String postgresJdbcUser,
		@Value("${postgres.jdbcPassword}") String postgresJdbcPassword) {

	DataSource targetDataSource = DataSourceBuilder
			.create()
			.driverClassName(postgresJdbcDriver)
			.url(postgresJdbcUrl)
			.username(postgresJdbcUser)
			.password(postgresJdbcPassword)
			.build();

	return new JdbcTemplate(targetDataSource);
}
 
Example #8
Source File: DataSourceConfig.java    From tinyid with Apache License 2.0 6 votes vote down vote up
private DataSource buildDataSource(String dataSourceType, Map<String, Object> dsMap) {
    try {
        String className = DEFAULT_DATASOURCE_TYPE;
        if (dataSourceType != null && !"".equals(dataSourceType.trim())) {
            className = dataSourceType;
        }
        Class<? extends DataSource> type = (Class<? extends DataSource>) Class.forName(className);
        String driverClassName = dsMap.get("driver-class-name").toString();
        String url = dsMap.get("url").toString();
        String username = dsMap.get("username").toString();
        String password = dsMap.get("password").toString();

        return DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password)
                .type(type)
                .build();

    } catch (ClassNotFoundException e) {
        logger.error("buildDataSource error", e);
        throw new IllegalStateException(e);
    }
}
 
Example #9
Source File: TccConfig.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
public DataSource tccDataSource() {
    return DataSourceBuilder.create()
            .type(properties.getType())
            .driverClassName(properties.getDriverClassName())
            .url(properties.getUrl())
            .username(properties.getUsername())
            .password(properties.getPassword())
            .build();
}
 
Example #10
Source File: DataBaseConfiguration.java    From MI-S with MIT License 5 votes vote down vote up
/**
 * 从库配置(负责读)
 * @return
 */
@Bean(name = "slaveDataSourceOne")
@ConfigurationProperties(prefix = "spring.slave",locations = "classpath:application.properties")
public DataSource readDataSourceOne(){
    log.info("-------------------- Slave DataSource One init ---------------------");
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example #11
Source File: DataBaseConfiguration.java    From MI-S with MIT License 5 votes vote down vote up
/**
 * 主库配置(负责写)
 * @return
 */
@Bean(name="masterDataSource", destroyMethod = "close", initMethod="init")
@Primary
@ConfigurationProperties(prefix = "spring.datasource",locations = "classpath:application.properties")
public DataSource writeDataSource() {
    log.info("-------------------- Master DataSource init ---------------------");
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example #12
Source File: DataBaseConfiguration.java    From MI-S with MIT License 5 votes vote down vote up
/**
 * 主库配置(负责写)
 * @return
 */
@Bean(name="masterDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource writeDataSource() {
    log.info("-------------------- Master DataSource init ---------------------");
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example #13
Source File: SqlRewriterConfiguration.java    From calcite-sql-rewriter with Apache License 2.0 5 votes vote down vote up
@Bean
@ConfigurationProperties("calcite.datasource")
public DataSource calciteDataSource(@Autowired String inlineModel) {
	DataSource dataSource = DataSourceBuilder
			.create()
			.driverClassName("org.apache.calcite.jdbc.Driver")
			.url("jdbc:calcite:lex=JAVA;model=inline:" + inlineModel)
			.build();

	log.info("Generated Calcite mode: " + inlineModel);
	return dataSource;
}
 
Example #14
Source File: OauthServerMain.java    From spring-oauth-example with MIT License 5 votes vote down vote up
/**
 * Main data source containing the credentials.
 * In this is example this is the DB from the resource server.
 */
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource mainDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example #15
Source File: DBConfig.java    From MonitorClient with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.sqlite.JDBC");
    dataSourceBuilder.url("jdbc:sqlite:config/config.db");
    return dataSourceBuilder.build();
}
 
Example #16
Source File: TccConfig.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
public DataSource tccDataSource() {
    return DataSourceBuilder.create()
            .type(properties.getType())
            .driverClassName(properties.getDriverClassName())
            .url(properties.getUrl())
            .username(properties.getUsername())
            .password(properties.getPassword())
            .build();
}
 
Example #17
Source File: AppConfiguration.java    From TAC with MIT License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource.tac")
public DataSource dataSource() {
    // 使用内嵌的hsqldb作为DEMO的测试
    // return new EmbeddedDatabaseBuilder().addScript("schema.sql").build();
    // 日常使用spring-data数据源或者其他开源的数据库连接池
     return DataSourceBuilder.create().build();
}
 
Example #18
Source File: TccConfig.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
public DataSource tccDataSource() {
    return DataSourceBuilder.create()
            .type(properties.getType())
            .driverClassName(properties.getDriverClassName())
            .url(properties.getUrl())
            .username(properties.getUsername())
            .password(properties.getPassword())
            .build();
}
 
Example #19
Source File: DataSourceConfig.java    From multitenancy with GNU General Public License v2.0 5 votes vote down vote up
@Bean(name = { "dataSource", "dataSource1" })
@ConfigurationProperties(prefix = "spring.multitenancy.datasource1")
public DataSource dataSource1() {
	DataSourceBuilder factory = DataSourceBuilder
			.create(this.multitenancyProperties.getDatasource1().getClassLoader())
			.driverClassName(this.multitenancyProperties.getDatasource1().getDriverClassName())
			.username(this.multitenancyProperties.getDatasource1().getUsername())
			.password(this.multitenancyProperties.getDatasource1().getPassword())
			.url(this.multitenancyProperties.getDatasource1().getUrl());
	return factory.build();
}
 
Example #20
Source File: AppConfig.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 5 votes vote down vote up
@Bean(name = "dataSource")
public DataSource getDataSource() {
    DataSource dataSource = DataSourceBuilder
            .create()
            .username(username)
            .password(password)
            .url(url)
            .driverClassName(driverClassName)
            .build();
    return dataSource;
}
 
Example #21
Source File: AppConfig.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 5 votes vote down vote up
@Bean(name = "dataSource")
public DataSource getDataSource() {
    DataSource dataSource = DataSourceBuilder
            .create()
            .username(username)
            .password(password)
            .url(url)
            .driverClassName(driverClassName)
            .build();
    return dataSource;
}
 
Example #22
Source File: DataSourceConfiguration.java    From javabase with Apache License 2.0 5 votes vote down vote up
@Bean(name = "writeDataSource")
@Primary
@ConfigurationProperties(prefix = "datasource.write")
public DataSource writeDataSource() {
	log.info("-------------------- writeDataSource init ---------------------");
	return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example #23
Source File: DBConfig.java    From MonitorClient with Apache License 2.0 5 votes vote down vote up
/**
 * 索引数据库配置
 * @data 2017年3月11日
 * @param indexPath 数据库存储位置
 * @return
 */
public DataSource indexDataSource(String indexPath) {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.sqlite.JDBC");
    dataSourceBuilder.url("jdbc:sqlite:"+indexPath);
    return dataSourceBuilder.build();
}
 
Example #24
Source File: MultitenantConfiguration.java    From spring-multi-tenant-demo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the default data source for the application
 * @return
 */
private DataSource defaultDataSource() {
    DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(this.getClass().getClassLoader())
            .driverClassName(properties.getDriverClassName())
            .url(properties.getUrl())
            .username(properties.getUsername())
            .password(properties.getPassword());

    if(properties.getType() != null) {
        dataSourceBuilder.type(properties.getType());
    }

    return dataSourceBuilder.build();
}
 
Example #25
Source File: PersistenceService.java    From state-machine with Apache License 2.0 5 votes vote down vote up
private static DataSource createDataSource() {
	log.info("creating data source");
	try {
		// create a new file based db in target on every startup
		File file = File.createTempFile("test", "db", new File("target"));
		return DataSourceBuilder //
				.create() //
				.url("jdbc:h2:file:" + file.getAbsolutePath()) //
				.driverClassName(Driver.class.getName()) //
				.build();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}

}
 
Example #26
Source File: TeiidTestDataSources.java    From monolith with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource legacyDS() {

    DataSource dataSource = DataSourceBuilder.create().driverClassName("org.h2.Driver").username("sa").password("").url("jdbc:h2:mem:legacydb;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=FALSE;MODE=MYSQL").build();

    Resource initSchema = new ClassPathResource("h2/scripts/legacydb-schema.sql");
    Resource initData = new ClassPathResource("h2/scripts/legacydb-data.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);
    return dataSource;
}
 
Example #27
Source File: TeiidTestDataSources.java    From monolith with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource ordersDS() {
    DataSource dataSource = DataSourceBuilder.create().driverClassName("org.h2.Driver").username("sa").password("").url("jdbc:h2:mem:ordersdb;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=FALSE;MODE=MYSQL").build();

    Resource initSchema = new ClassPathResource("h2/scripts/ordersdb-schema.sql");
    Resource initData = new ClassPathResource("h2/scripts/ordersdb-data.sql");
    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
    DatabasePopulatorUtils.execute(databasePopulator, dataSource);
    return dataSource;
}
 
Example #28
Source File: JdbcHdfsDataSourceConfiguration.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean(name="jdbchdfsDataSource")
public DataSource jdbcHdfsDataSource() {
	DataSource dataSource;
	if(props.getUrl() != null && props.getUsername() != null) {
		dataSource = DataSourceBuilder.create().driverClassName(props.getDriverClassName())
			.url(props.getUrl())
			.username(props.getUsername())
			.password(props.getPassword()).build();
	} else {
		dataSource = getDefaultDataSource();
	}
	return dataSource;
}
 
Example #29
Source File: JpaConfig.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName(driverClassName);
    dataSourceBuilder.url(url);
    dataSourceBuilder.type(HikariDataSource.class);
    return dataSourceBuilder.build();
}
 
Example #30
Source File: DataSourceConfiguration.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
 * 有多少个从库就要配置多少个
 * @return
 */
@Bean(name = "readDataSource1")
@ConfigurationProperties(prefix = "datasource.read1")
public DataSource readDataSourceOne() {
	log.info("-------------------- readDataSourceOne init ---------------------");
	return DataSourceBuilder.create().type(dataSourceType).build();
}