关于spring boot jdbctemple多数据源重用通用配置

时间:2017-06-26 10:28:39

标签: spring-boot jdbctemplate

我使用了spring boot + jdbctemplate,在我的业务中我必须访问多数据源,例如。

application.properties

foo.datasource.url=jdbc:mysql://127.0.0.1/foo
foo.datasource.username=root
foo.datasource.password=12345678

bar.datasource.url=jdbc:mysql://127.0.0.1/bar
bar.datasource.username=root
bar.datasource.password=12345678

Java Config

@Bean(name = "fooDb")
@ConfigurationProperties(prefix = "foo.datasource")
public DataSource fooDataSource() {
    return DataSourceBuilder.create().build();
}
@Bean(name = "fooJdbcTemplate")
public JdbcTemplate fooJdbcTemplate(@Qualifier("fooDb") DataSource ds) {
    return new JdbcTemplate(ds);
}

并且所有数据源都有一些通用配置

spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

我如何将这些常用属性填充到每个jdbctemplate中,例如

@Bean(name = "commonDb")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource commonDataSource() {
    return DataSourceBuilder.create().build();
}

1 个答案:

答案 0 :(得分:0)

现在我的方式是

@Value("${spring.datasource.test-while-idle}")
private boolean  testWhileIdle;
@Value("${spring.datasource.time-between-eviction-runs-millis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.validation-query}")
private String validationQuery;


private DataSource commonProcess(DataSource build) {
    org.apache.tomcat.jdbc.pool.DataSource ds = (org.apache.tomcat.jdbc.pool.DataSource) build;
    ds.setTestWhileIdle(testWhileIdle);
    ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    ds.setValidationQuery(validationQuery);

    return build;
}


@Bean(name = "fooDb")
@ConfigurationProperties(prefix = "foo.datasource")
public DataSource fooDataSource() {
    return commonProcess(DataSourceBuilder.create().build());
}