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

The following are top voted examples for showing how to use org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: amv-access-api-poc   File: EmbeddedMySqlConfig.java   Source Code and License 7 votes vote down vote up
@Primary
@Bean(destroyMethod = "close")
public DataSource dataSource() {
    final EmbeddedMysql embeddedMysql = embeddedMysql(); // make sure embeddedMySql is started.

    Map<String, String> params = ImmutableMap.<String, String>builder()
            .put("profileSQL", String.valueOf(false))
            .put("generateSimpleParameterMetadata", String.valueOf(true))
            .build();

    final String url = String.format("jdbc:mysql://localhost:%d/%s?%s",
            embeddedMysql.getConfig().getPort(),
            SCHEMA_NAME,
            Joiner.on("&").withKeyValueSeparator("=").join(params));

    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.username(embeddedMysql.getConfig().getUsername());
    dataSourceBuilder.password(embeddedMysql.getConfig().getPassword());
    dataSourceBuilder.driverClassName(com.mysql.jdbc.Driver.class.getName());
    dataSourceBuilder.url(url);
    return dataSourceBuilder.build();
}
 
Example 2
Project: calcite-sql-rewriter   File: SqlRewriterConfiguration.java   Source Code and License 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 3
Project: BackOffice   File: DataBaseCaller.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @return экземпляр JDBCTemplate Для работы с тестовой базой данных
 */
public Database getFirstFunctionalInstance(){
    if (firstFunctionalInstance == null) {
        LOG.debug("Инициируем новый инстанс базы данных");
        DataSource ds = DataSourceBuilder
                .create()
                .username(databaseUser)
                .password(databasePassword)
                .url("jdbc:sqlserver://192.168.20.28:49484;instance=maindb")
                .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                .build();
        this.firstFunctionalInstance = new Database(ds);
        return firstFunctionalInstance;
    }
    else {
        LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий");
        return firstFunctionalInstance;}
}
 
Example 4
Project: BackOffice   File: DataBaseCaller.java   Source Code and License 6 votes vote down vote up
public Database getFirstFunctionalInstance(String databaseName){
    if (firstFunctionalInstance == null) {
        LOG.debug("Инициируем новый инстанс базы данных");
        DataSource ds = DataSourceBuilder
                .create()
                .username(databaseUser)
                .password(databasePassword)
                .url("jdbc:sqlserver://192.168.20.28:49484;instance=maindb;databaseName="+databaseName)
                .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                .build();
        this.firstFunctionalInstance = new Database(ds);
        return firstFunctionalInstance;
    }
    else {
        LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий");
        return firstFunctionalInstance;}
}
 
Example 5
Project: BackOffice   File: DataBaseCaller.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @return экземпляр JDBCTemplate Для работы с базой данных нагрузочного стенда
 */
public Database getLoadInstance(){
    if (loadInstance == null) {
        LOG.debug("Инициируем новый инстанс базы данных");
        DataSource ds = DataSourceBuilder
                .create()
                .username(databaseUser)
                .password(databasePassword)
                .url("jdbc:sqlserver://192.168.21.9;instance=maindb")
                .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                .build();
        this.loadInstance = new Database(ds);
        return loadInstance;
    }
    else {
        LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий");
        return loadInstance;}
}
 
Example 6
Project: spring-boot-multidatasource   File: DataSourceInitializer.java   Source Code and License 6 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
	if (resources.isEmpty()) {
		return;
	}
	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);
	}
	DataSource dataSource = this.dataSource;
	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 7
Project: participationSystem3a   File: DataSourceBean.java   Source Code and License 6 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
	ConnectionData conData = getDbUrl();
	return DataSourceBuilder
			.create()
			.url(conData.getUrl() + "?sslmode=require")
			.username(conData.getUser())
			.password(conData.getPassword())
			.driverClassName("org.postgresql.Driver")
			.build();
}
 
Example 8
Project: micro-service-sample   File: ReadonlySourceConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
	@ConfigurationProperties(prefix="spring.datasource.readonly")
	public DataSource readonlyDataSource() throws SQLException {
		DruidDataSource dataSource = (DruidDataSource)DataSourceBuilder
					.create()
					.type(DruidDataSource.class)
					.build();
//		dataSource.setFilters("wall");
		/*
		WallFilter wallFilter = new WallFilter();
		wallFilter.setLogViolation(true);
		wallFilter.setThrowException(false);
		dataSource.getProxyFilters().add(wallFilter);
		*/
	    return dataSource;
	}
 
Example 9
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 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 10
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 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 11
Project: c2mon   File: ConfigDataSourceConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@org.springframework.boot.context.properties.ConfigurationProperties(prefix = "c2mon.server.configuration.jdbc")
public DataSource configurationDataSource() {
  String url = properties.getJdbc().getUrl();
  String username = properties.getJdbc().getUsername();
  String password = properties.getJdbc().getPassword();
  

  // 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")) {
    return new HsqlDatabaseBuilder()
               .url(url)
               .username(username)
               .password(password)
               .addScript(new ClassPathResource("sql/config-schema-hsqldb.sql")).build();
  } else {
    return DataSourceBuilder.create().build();
  }
}
 
Example 12
Project: c2mon   File: HistoryDataSourceConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@ConfigurationProperties("c2mon.server.history.jdbc")
public DataSource historyDataSource() {
  String url = properties.getJdbc().getUrl();
  String username = properties.getJdbc().getUsername();
  String password = properties.getJdbc().getPassword();

  if (url.contains("hsql")) {
    return new HsqlDatabaseBuilder()
               .url(url)
               .username(username)
               .password(password)
               .addScript(new ClassPathResource("sql/history-schema-hsqldb.sql")).build();
  } else {
    return DataSourceBuilder.create().build();
  }
}
 
Example 13
Project: c2mon   File: HsqlDatabaseBuilder.java   Source Code and License 6 votes vote down vote up
public DataSource build() {
  DataSource dataSource;

  if (url == null || url.contains("hsqldb:mem")) {
    // Start an in-process, in-memory HSQL server
    dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build();
  } else if (url.contains("hsql://")) {
    // Start an externally visible, file-based HSQL server
    HsqlServer.start("file:///tmp/c2mondb", "c2mondb");
    url += ";sql.syntax_ora=true;hsqldb.default_table_type=cached;hsqldb.cache_rows=1000;hsqldb.result_max_memory_rows=2000;hsqldb.cache_size=100";
    dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build();

  } else {
    throw new RuntimeException("The given URL was not a valid HSQL JDBC URL!");
  }

  if (!scripts.isEmpty()) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()]));
    populator.setContinueOnError(true);
    DatabasePopulatorUtils.execute(populator, dataSource);
  }

  return dataSource;
}
 
Example 14
Project: c2mon   File: CacheDataSourceConfig.java   Source Code and License 6 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "c2mon.server.cachedbaccess.jdbc")
public DataSource cacheDataSource() {
  String url = properties.getJdbc().getUrl();
  String username = properties.getJdbc().getUsername();
  String password = properties.getJdbc().getPassword();

  // 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")) {
    return new HsqlDatabaseBuilder()
               .url(url)
               .username(username)
               .password(password)
               .addScript(new ClassPathResource("sql/cache-schema-hsqldb.sql")).build();
  } else {
    return DataSourceBuilder.create().build();
  }
}
 
Example 15
Project: Dynamic-data-sources   File: DynamicDataSourceRegister.java   Source Code and License 6 votes vote down vote up
/**
 * 创建DataSource
 */
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
    try {
        Object type = dsMap.get("type");
        if (type == null)
            type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource

        Class<? extends DataSource> dataSourceType;
        dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);

        String driverClassName = dsMap.get("driverClassName").toString();
        String url = dsMap.get("url").toString();
        String username = dsMap.get("username").toString();
        String password = dsMap.get("password").toString();

        DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
                .username(username).password(password).type(dataSourceType);
        return factory.build();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 16
Project: kekoa   File: DynamicDataSourceRegister.java   Source Code and License 6 votes vote down vote up
/**
 * 创建DataSource
 *
 * @param type
 * @param driverClassName
 * @param url
 * @param username
 * @param password
 * @return
 * @author SHANHY
 * @create 2016年1月24日
 */
@SuppressWarnings("unchecked")
public DataSource buildDataSource(Map<String, Object> dsMap) {
    try {
        Object type = dsMap.get("type");
        if (type == null)
            type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource

        Class<? extends DataSource> dataSourceType;
        dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);

        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();

        DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url)
                .username(username).password(password).type(dataSourceType);
        return factory.build();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 17
Project: apparel   File: DatabaseConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public DataSource dataSourceProd() {
    String databaseUrl = env.getProperty("database.url");
    String databaseUsername = env.getProperty("database.username");
    String databasePassword = env.getProperty("database.password");

    if(databaseUrl == null || databaseUsername == null || databasePassword == null) {
        logger.log(Level.ALL, "Using local H2 database");
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }

    logger.log(Level.ALL, "Using database " + databaseUrl);
    return DataSourceBuilder.create()
            .url(databaseUrl)
            .username(databaseUsername)
            .password(databasePassword)
            .build();

}
 
Example 18
Project: blackhole   File: DatabaseConfiguration.java   Source Code and License 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 19
Project: workflow-catalog-old   File: Application.java   Source Code and License 6 votes vote down vote up
@Bean
@Profile("default")
public DataSource defaultDataSource() {
    String jdbcUrl = dataSourceUrl;

    if (jdbcUrl.isEmpty()) {
        jdbcUrl = "jdbc:hsqldb:file:" + getDatabaseDirectory() +
                  ";create=true;hsqldb.tx=mvcc;hsqldb.applog=1;hsqldb.sqllog=0;hsqldb.write_delay=false";
    }

    return DataSourceBuilder.create()
                            .username(dataSourceUsername)
                            .password(dataSourcePassword)
                            .url(jdbcUrl)
                            .driverClassName(dataSourceDriverClassName)
                            .build();
}
 
Example 20
Project: REST-Web-Services   File: WebDatasourceConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Get data source.
 *
 * @return Data source
 */
@Primary
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource getDatasource() {
    return DataSourceBuilder.create().build();
}
 
Example 21
Project: read-write-sever   File: DatabaseConfig.java   Source Code and License 5 votes vote down vote up
@Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource writeDataSource() {
    logger.info("初始化写入数据源……");
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example 22
Project: read-write-sever   File: DatabaseConfig.java   Source Code and License 5 votes vote down vote up
/**
 * 有多少个从库就要配置多少个
 * @return
 */
@Bean(name = "readDataSource")
@ConfigurationProperties(prefix = "custom.datasource.read")
public DataSource readDataSource(){
    logger.info("初始化读数据源……");
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example 23
Project: amv-access-api-poc   File: SqliteTestDatabaseConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName(org.sqlite.JDBC.class.getName());
    dataSourceBuilder.url("jdbc:sqlite:~amv-access-test.db?journal_mode=wal");
    return dataSourceBuilder.build();
}
 
Example 24
Project: amv-access-api-poc   File: SwaggerSqliteTestDatabaseConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public DataSource dataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName(org.sqlite.JDBC.class.getName());
    dataSourceBuilder.url("jdbc:sqlite:~amv-access-swagger-docs.db?journal_mode=wal");
    return dataSourceBuilder.build();
}
 
Example 25
Project: springboot-smart   File: DataBaseConfigration.java   Source Code and License 5 votes vote down vote up
@Bean(name = "writeDataSource", destroyMethod = "close", initMethod = "init")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource writeDataSource() {
	log.info("-------------------- writeDataSource init ---------------------");
	return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example 26
Project: druid-spring-boot   File: DruidDataSourceInitializer.java   Source Code and License 5 votes vote down vote up
private void runScripts(List<Resource> resources, String username, String password) {
    if (resources.isEmpty()) {
        return;
    }
    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);
    }
    DataSource dataSource = this.dataSource;
    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 27
Project: druid-boot-starter   File: DruidAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@ConfigurationProperties(DruidProperties.DRUID_PREFIX)
public DataSource dataSource(DruidProperties properties) {
    DruidDataSource datasource = (DruidDataSource) DataSourceBuilder
            .create()
            .type(DruidDataSource.class)
            .build();
    configDruid(datasource, properties);
    return datasource;
}
 
Example 28
Project: calcite-sql-rewriter   File: SqlRewriterConfiguration.java   Source Code and License 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 29
Project: MI-S   File: DataBaseConfiguration.java   Source Code and 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 30
Project: MI-S   File: DataBaseConfiguration.java   Source Code and 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 31
Project: MI-S   File: DataBaseConfiguration.java   Source Code and 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 32
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: AppConfig.java   Source Code and 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 33
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: AppConfig.java   Source Code and 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 34
Project: activiti-analytics-spring-boot   File: AnalyticsConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource activitiDataSource() {
	logger.debug("creating activitiDataSource bean");
	return DataSourceBuilder.create().build();
}
 
Example 35
Project: mybatis-migrations-spring-boot-autoconfigure   File: MyBatisMigrationsAutoConfiguration.java   Source Code and License 5 votes vote down vote up
private DataSource getDataSource() {
	if (this.myBatisMigrationsDataSource != null) {
		return this.myBatisMigrationsDataSource;
	}

	if (this.properties.getUrl() == null) {
		return this.dataSource;
	}

	return DataSourceBuilder.create().url(this.properties.getUrl())
			.username(this.properties.getUser())
			.password(this.properties.getPassword()).build();
}
 
Example 36
Project: klask-io   File: DatabaseConfiguration.java   Source Code and License 5 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 37
Project: data-migration   File: DataSourceConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
@Qualifier("jpaDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource createJpaDataSource() {
    return DataSourceBuilder.create().type(dataSourceType).build();
}
 
Example 38
Project: integrate-activiti-with-spring   File: IntegrateActivitiWithSpringApplication.java   Source Code and License 5 votes vote down vote up
/**
 * Activiti's user guide - 5.7.3. Changing the database and connection pool
 * https://www.activiti.org/userguide/index.html#_changing_the_database_and_connection_pool
 **/
@Bean(name = "datasource.activiti")
public DataSource activitiDataSource() {
	return DataSourceBuilder.create(this.dataSourceproperties.getClassLoader())
			.url(this.dataSourceproperties.getUrl())
			.username(this.dataSourceproperties.getUsername())
			.password(this.dataSourceproperties.getPassword())
			.driverClassName(this.dataSourceproperties.getDriverClassName())
	        .build();
}
 
Example 39
Project: spring-boot-starter-dynamic-datasource   File: DynamicDataSourceRegister.java   Source Code and License 5 votes vote down vote up
/**
 * @param dataSourceClassType
 * @return
 * @Title: buildDataSource
 * @Description: 根据数据源class类型创建数据源
 * @author Kola 6089555
 * @date 2017年4月24日 下午6:46:47
 */
@SuppressWarnings("unchecked")
public DataSource buildDataSource(String dataSourceClassType) {
    DataSource dataSource = null;
    try {
        if (StringUtils.isBlank(dataSourceClassType))
            dataSourceClassType = DATASOURCE_TYPE_DEFAULT;
        Class<? extends DataSource> dataSourceType = (Class<? extends DataSource>) Class.forName(dataSourceClassType);
        dataSource = DataSourceBuilder.create().type(dataSourceType).build();
    } catch (ClassNotFoundException e) {
        LOGGER.error("buildDataSource failure.because {}", e.getMessage());
        e.printStackTrace();
    }
    return dataSource;
}
 
Example 40
Project: sample-schedule-job-admin   File: WebMvc.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource getDataSource() {
	return DataSourceBuilder
            .create()
            .driverClassName("org.hsqldb.jdbcDriver")
            .url("jdbc:hsqldb:file:" + new File(Utils.getBase(), "db").getPath() + "/store")
            .username("iisi")
            .password("")
            .build();
}
 
Example 41
Project: WebIDE-Backend   File: JpaConfig.java   Source Code and 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 42
Project: javabase   File: DataSourceConfiguration.java   Source Code and License 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 43
Project: javabase   File: DataSourceConfiguration.java   Source Code and License 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();
}
 
Example 44
Project: jhipster-ribbon-hystrix   File: DatabaseConfiguration.java   Source Code and License 5 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 45
Project: imageboard   File: ConfigDataSource.java   Source Code and License 5 votes vote down vote up
@Bean
@Qualifier("dataSource")
public DataSource buildDataSourceDev() {
    DataSourceBuilder dsb = DataSourceBuilder.create();
    dsb.driverClassName(driver);
    dsb.url(url);
    dsb.username(username);
    dsb.password(password);
    return dsb.build();
}
 
Example 46
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource.test")
public DataSource dataSource() {
	return DataSourceBuilder.create()
			.driverClassName("org.hsqldb.jdbc.JDBCDriver")
			.url("jdbc:hsqldb:mem:test").username("sa").build();
}
 
Example 47
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: LiquibaseAutoConfiguration.java   Source Code and License 5 votes vote down vote up
private DataSource getDataSource() {
	if (this.properties.getUrl() == null) {
		return this.dataSource;
	}
	return DataSourceBuilder.create().url(this.properties.getUrl())
			.username(this.properties.getUser())
			.password(this.properties.getPassword()).build();
}
 
Example 48
Project: c2mon-web-ui   File: StatisticsDataSourceConfig.java   Source Code and License 5 votes vote down vote up
@Bean
@Primary
public DataSource statisticsDataSource() {
  return DataSourceBuilder.create()
      .url(environment.getProperty("c2mon.web.statistics.jdbc.url"))
      .username(environment.getProperty("c2mon.web.statistics.jdbc.username"))
      .password(environment.getProperty("c2mon.web.statistics.jdbc.password")).build();
}
 
Example 49
Project: SpringBootUnity   File: MultipleSourceMain.java   Source Code and License 5 votes vote down vote up
/**
 * 第一个数据源
 * @return 数据源实例
 */
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example 50
Project: SpringBootUnity   File: MultipleSourceMain.java   Source Code and License 5 votes vote down vote up
/**
 * 第二个数据源
 * @return 数据源实例
 */
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}
 
Example 51
Project: spring-multi-tenant-demo   File: MultitenantConfiguration.java   Source Code and License 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 52
Project: springJpaKata   File: ProxyDsConfig.java   Source Code and License 5 votes vote down vote up
@Bean
public DataSource actualDataSource() {
    return DataSourceBuilder
            .create(ProxyDsConfig.class.getClassLoader())
            .driverClassName("org.h2.Driver")
            .url("jdbc:h2:mem:testdb")  // in-memory db
            .username("sa")
            .password("")
            .build();
}
 
Example 53
Project: spring-boot-concourse   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.datasource.test")
public DataSource dataSource() {
	return DataSourceBuilder.create()
			.driverClassName("org.hsqldb.jdbc.JDBCDriver")
			.url("jdbc:hsqldb:mem:test").username("sa").build();
}
 
Example 54
Project: spring-boot-concourse   File: LiquibaseAutoConfiguration.java   Source Code and License 5 votes vote down vote up
private DataSource getDataSource() {
	if (this.properties.getUrl() == null) {
		return this.dataSource;
	}
	return DataSourceBuilder.create().url(this.properties.getUrl())
			.username(this.properties.getUser())
			.password(this.properties.getPassword()).build();
}
 
Example 55
Project: contestparser   File: HealthIndicatorAutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
public DataSource dataSource() {
	return DataSourceBuilder.create()
			.driverClassName("org.hsqldb.jdbc.JDBCDriver")
			.url("jdbc:hsqldb:mem:test").username("sa").build();
}
 
Example 56
Project: contestparser   File: LiquibaseAutoConfiguration.java   Source Code and License 5 votes vote down vote up
private DataSource getDataSource() {
	if (this.properties.getUrl() == null) {
		return this.dataSource;
	}
	return DataSourceBuilder.create().url(this.properties.getUrl())
			.username(this.properties.getUser())
			.password(this.properties.getPassword()).build();
}
 
Example 57
Project: onetwo   File: DynamicDataSource.java   Source Code and License 5 votes vote down vote up
protected void scanDatasources(){
	Map<String, DsProperties> dsConfig = this.datasourceRouterProperties.getTargets();
	ValueHolder<DataSource> dsHouder = new ValueHolder<>(null);
	Map<Object, Object> targetDataSources = Maps.newLinkedHashMap();
	dsConfig.forEach((key, props)->{
		props.putAll(datasourceRouterProperties.getCommon());
		
		DataSource ds = DataSourceBuilder.create()
							.driverClassName(props.getDriverClassName())
							.url(props.getUrl())
							.username(props.getUsername())
							.password(props.getPassword())
							.build();
		BeanPropertiesMapper mapper = new BeanPropertiesMapper(props, null);
		mapper.mapToObject(ds);
		targetDataSources.put(key, ds);
		if(props.getBoolean("default", false)){//是否作为默认数据源
			dsHouder.setValue(ds);
		}
	});
	if(dsHouder.hasValue()){
		this.setDefaultTargetDataSource(dsHouder.getValue());
	}else if(!targetDataSources.isEmpty()){
		this.setDefaultTargetDataSource(targetDataSources.values().iterator().next());
	}else{
		throw new BaseException("default datasource not found!");
	}
	this.setTargetDataSources(targetDataSources);
}
 
Example 58
Project: springboot-tourreservation   File: Config.java   Source Code and License 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
DataSource realDataSource() {
    DataSource dataSource = DataSourceBuilder
            .create(this.dataSourceProperties.getClassLoader())
            .url(this.dataSourceProperties.getUrl())
            .username(this.dataSourceProperties.getUsername())
            .password(this.dataSourceProperties.getPassword())
            .build();
    return dataSource;
}
 
Example 59
Project: spring-file-upload-storage   File: FileUploadConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Provides a {@code DataSource} for file upload storage. The {@code DataSource} must have the qualifier
 * 'spring-file-upload-storage'.
 * <p>This implementation creates an H2 database in the servlet container's temporary directory.</p>
 * <p>Using a temporary database works well enough for demonstrations, but for production-level applications you may
 * want to connect to your app's existing database.</p>
 *
 * @param servletContext
 * @return
 */
@Bean
@Qualifier("spring-file-upload-storage")
DataSource fileUploadDataSource(ServletContext servletContext) {
  File tempDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
  File databaseFile = new File(tempDir, "spring-file-upload-storage");
  String filename = databaseFile.getAbsolutePath();
  logger.info("File uploads are stored in '{}.h2.db'.", filename);
  return DataSourceBuilder.create()
      .driverClassName("org.h2.Driver")
      .url("jdbc:h2:file:" + filename)
      .username("sa")
      .build();
}
 
Example 60
Project: grassroot-platform   File: StagingDatabaseConfig.java   Source Code and License 5 votes vote down vote up
@Override
public DataSource dataSource() {
    log.info("Running with STAGING profile");
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url(System.getenv("DATABASE_URL"));
    return dataSourceBuilder.build();
}