ngeek
ngeek

Reputation: 7903

How to configure database configuration connection pooling with custom prefix in Spring Boot?

Consider Spring Boot with spring-boot-starter-jdbc and that you would like to have one or more Data Sources, which do have a custom prefix in their property names. From what I see in org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration it looks to me, that the auto-configuration can only be used with the default prefix spring.datasource, but as soon as you modify it, you will be on your own setting up the properties regarding pooling.

Can someone please shed light on how to configure the Tomcat JDBC Pool DataSource more elegant (read Spring idiomatic)?

Current work around:

@Configuration
public class DatabaseConfiguration {

    @Value("${datasource.api.tomcat.maxWait:5000}")
    private int maxWaitMillis;

    @Value("${datasource.api.tomcat.test-on-borrow:true}")
    private boolean testOnBorrow;

    @Value("${datasource.api.tomcat.validation-query:SELECT 1}")
    private String validationQuery;

    @Bean(name = "apiDataSource")
    @ConfigurationProperties(prefix = "datasource.api")
    public DataSource apiDataSource() {
        DataSource ds = DataSourceBuilder.create().build();
        // Assume we make use of Apache Tomcat connection pooling (default in Spring Boot)
        org.apache.tomcat.jdbc.pool.DataSource tds = (org.apache.tomcat.jdbc.pool.DataSource) ds;
        tds.setTestOnBorrow(testOnBorrow);
        tds.setValidationQuery(validationQuery);
        tds.setMaxWait(maxWaitMillis);
        return ds;
    }
}

Upvotes: 0

Views: 1741

Answers (1)

ngeek
ngeek

Reputation: 7903

Actually it turned out to be quite straight-forward thanks to the binding feature of Spring Boot's ConfigurationProperties annotation, you can directly populate the JDBC connection pool properties in the following fashion and avoid therefore the cumbersome initialisation of each property on its own:

@Bean
@ConfigurationProperties(prefix = "datasource.api")
public PoolProperties apiPoolProperties() {
    return new org.apache.tomcat.jdbc.pool.PoolProperties();
}

@Bean(name = "apiDataSource")
public DataSource apiDataSource(@Qualifier("apiPoolProperties") PoolProperties poolProperties) {
    DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
    logger.info("Initialized API Datasource: {}", ds);
    return ds;
}

Upvotes: 1

Related Questions