13

在 Spring Boot 应用程序中,我想使用@ConfigurationProperties具有相同前缀的注释来根据配置文件配置我的两个数据源。为什么 Spring Boot 配置处理器禁止它?gradle报错是:

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

笔记:

  • “运行方式-> Spring Boot App”在 STS 中有效
  • 没有 spring-boot-configuration-processor 依赖,gradle build 工作(但When using @ConfigurationProperties it is recommended to add 'spring-boot-configuration-processor' to your classpath to generate configuration metadata出现警告)

构建.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")
}

应用程序属性

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

你好。申请

@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();
    }

}

提前致谢

4

1 回答 1

1

我认为您对它的工作原理感到困惑。代码应该大部分保持不变。当您定义启动时要加载的配置文件时,这些属性会发生变化。

应用程序-dev.properties

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

应用程序-prod.properties

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

并且只有一个 bean 设置了数据源。

于 2017-08-19T02:17:39.810 回答