Search code examples
springspring-bootspring-jdbc

Why is @ConfigurationProperties needed in building a DataSource in Spring?


If @ConfigurationProperties binds the properties into an object, what is the usage of @ConfigurationProperties in building a DataSource?

application.properties

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

Data Source Bean:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

Also, if the data source properties is already bound using @ConfigurationProperties in a separate bean, do we still need to put the same annotation to the Data Source builder bean?

@Bean
@ConfigurationProperties("database1.datasource")
public DataSourceProps dataSourceProps(){
    return new DataSourceProps();
}

@Bean(name = "datasource1")
// @ConfigurationProperties("database1.datasource") Is this necessary?
@Primary
public DataSource dataSource(){
    return dataSourceProps().initializeDataSourceBuilder().type(HikariDataSource.class).build();
}

Solution

  • No, you don't need to put @ConfigurationProperties("database1.datasource") on the second bean. It will not server any purpose. But if you put @ConfigurationProperties("database1.datasource.hikari") on the second bean it will configure your HikariDataSource. For example, you have a properties file like

    mysql.datasource.url=jdbc:mysql://localhost:3306/test
    mysql.datasource.username=root
    mysql.datasource.password=password
    mysql.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
    mysql.datasource.hikari.minimum-idle=3
    mysql.datasource.hikari.maximum-pool-size=8
    

    And your configuration is like

        @Bean
        @ConfigurationProperties("mysql.datasource")
        public DataSourceProperties mysqlDataSourceProperties() {
            return new DataSourceProperties();
        }
    
        @Bean
        @ConfigurationProperties("mysql.datasource.hikari")
        public DataSource mysqlDataSource() {
            return mysqlDataSourceProperties().initializeDataSourceBuilder()
                    .type(HikariDataSource.class).build();
        }
    

    The first bean creates a DataSourceProperties with database url, username and password which are provided with mysql.datasource.* . If you don't add @ConfigurationProperties("mysql.datasource.hikari") spring will configure hikari data connection pool with default values and you will not be able to change them by changing your property files. So two configuration properties server two different purpose.