74.1 Configure a DataSource

To override the default settings just define a @Bean of your own of type DataSource. As explained in Section 24.7.1, “Third-party configuration” you can easily bind it to a set of Environment properties:

_@Bean_
_@ConfigurationProperties(prefix="datasource.fancy")_
public DataSource dataSource() {
    return new FancyDataSource();
}
datasource.fancy.jdbcUrl=jdbc:h2:mem:mydb
datasource.fancy.username=sa
datasource.fancy.poolSize=30

Spring Boot also provides a utility builder class DataSourceBuilder that can be used to create one of the standard data sources (if it is on the classpath), or you can just create your own. If you want to reuse the customizations of DataSourceProperties, you can easily initialize a DataSourceBuilder from it:

_@Bean_
_@ConfigurationProperties(prefix="datasource.mine")_
public DataSource dataSource(DataSourceProperties properties) {
    return properties.initializeDataSourceBuilder()
            // additional customizations
            .build();
}
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.username=sa
datasource.mine.poolSize=30

In this scenario, you keep the standard properties exposed by Spring Boot with your custom DataSource arrangement. By adding @ConfigurationProperties, you can also expose additional implementation-specific settings in a dedicated namespace.

See Section 29.1, “Configure a DataSource” in the ‘Spring Boot features’ section and the DataSourceAutoConfiguration class for more details.

[Tip] Tip
You could also do that if you want to configure a JNDI data-source.

results matching ""

    No results matching ""