Spring Boot Configuration Processor, Duplicate @ConfigurationProperties definition for prefix

cmaulini picture cmaulini · Aug 18, 2017 · Viewed 9.5k times · Source

In a Spring Boot application, I want to use @ConfigurationProperties annotation with the same prefix to configure my two data sources depending to the profile. Why is it forbidden by Spring Boot Configuration Processor ? The error reported by gradle is:

...
:compileJava ... error: Duplicate `@ConfigurationProperties` definition for prefix 'spring.datasource'

Notes:

  • "Run As->Spring Boot App" works in STS
  • Without spring-boot-configuration-processor dependency, gradle build works (but the warning When using @ConfigurationProperties it is recommended to add 'spring-boot-configuration-processor' to your classpath to generate configuration metadata appears)

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.6.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

repositories {
    mavenCentral()
    maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile 'org.springframework.boot:spring-boot-configuration-processor:1.5.4.RELEASE'
    compile("com.h2database:h2")
}

application.properties

spring.datasource.driverClassName = org.h2.Driver
spring.datasource.username = sa
spring.datasource.password = sa

hello.Application

@SpringBootApplication
public class Application {

    public static void main(final String[] args) {
        final SpringApplication app = new SpringApplication(Application.class);
        app.setAdditionalProfiles("prod");
        app.run();
    }

    @Bean
    @Profile("dev")
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSourceDev() {
        return DataSourceBuilder
                .create()
                .url(generateDevUrl())
                .build();
    }

    @Bean
    @Profile("prod")
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSourceProd() {
        return DataSourceBuilder
                .create()
                .url(generateProdUrl())
                .build();
    }

}

Thanks in advance

Answer

ndrone picture ndrone · Aug 19, 2017

I think you are confused on how this works. The code should mostly stay the same. The properties change when you define which profile to load at start up.

application-dev.properties

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.url=

appilication-prod.properties

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.url=

And only one bean setup the datasource.