checketts
checketts

Reputation: 14943

How to extend Spring Boot's DataSourceAutoConfiguration

I want to be able to leverage the Spring Boot datasource auto-configuration. However it doesn't support all the features I'm using, logValidationErrors in particular.

spring:
  datasource:
    driverClassName: oracle.jdbc.OracleDriver
    url: jdbc:jtds:sqlserver://111.11.11.11/DataBaseName
    username: someuser
    password: somepass
    testOnBorrow: true
    testWhileIdle: true
    validationQuery: select /* validationQuery */ 1 from dual
    minEvictableIdleTimeMillis: 1000    
    validationInterval: 30000

These aren't currently used:

    logValidationErrors: true
    maxAge: 1800000 # //30 Minute idle age
    removeAbondoned: true

Can I just grab the created DataSource bean and set those values manually? Or is there a better way to extend or wrap the autoconfiguration?

See here for more about logValidationErrors, etc: https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html

Upvotes: 1

Views: 3640

Answers (3)

checketts
checketts

Reputation: 14943

I solved this with a BeanPostProcessor, similar to Dave Syer's suggestion:

@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof DataSource) {
        DataSource ds = (DataSource) bean;
        ds.setLogValidationErrors(true);
        ds.setRemoveAbandoned(true);
        ds.setMaxAge(1800000);
    }
    return bean;
}

I'll also likely submit a PR to get the properties added to Spring Boot itself.

Upvotes: 3

Dave Syer
Dave Syer

Reputation: 58094

If I were you I would just @Autowire the existing DataSource, downcast as necessary, and then set the extra property. It can be dangerous up do that for some beans (if they initialize themselves from their properties), but I doubt if that will be a problem here.

Upvotes: 1

Stephane Nicoll
Stephane Nicoll

Reputation: 33091

There are multiple ways you can fix this issue.

First, you may want to submit a pull request for TomcatDataSourceConfiguration against the spring boot project. Adding those dependencies is straightforward (look at validationInterval in the source code for an example.

Or, you could create your own datasource the way you want. If a DataSource bean is present, boot will not attempt to create its own. Then you could just extend from TomcatDataSourceConfiguration and add any property you want by overriding dataSource. Finally, you should import your extended class so that the bean is registered, which will disable auto-configuration for it.

If you chose that last option and that works for you, it might be worthwhile to still report an issue for those properties if you believe they could be interesting to a wider audience.

Upvotes: 2

Related Questions