简体   繁体   中英

@ConfigurationProperties same prefix for DB on two different beans

In my application properties I have

spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.validation-timeout=3000
spring.datasource.hikari.leak-detection-threshold=90000
spring.datasource.hikari.max-lifetime=3600000

and I have two datasource that is going to use the same configuration properties

    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    @Bean
    public HikariDataSource dataSource() throws Exception {
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    @Bean
    public HikariDataSource altDataSource() throws Exception {

It was working just a week ago, but now I am getting error when doing clean and build:

> Task :compileJava
error: Duplicate `@ConfigurationProperties` definition for prefix 'spring.datasource.hikari'
    public HikariDataSource altDataSource() throws Exception {

I have read a few varying solutions here, but is there a workaround other than editing my properties file? Because this was working a week ago, could this be an IDE issue?

Use Spring profiles likes this

class SomeOtherProfileConfig extends MyConfig {
}

@Profile("MyProfile")
@Bean(initMethod = "init", name = "MyConfig")
@ConfigurationProperties(prefix = "config")
public MyConfig config() {
    MyConfig config = new MyConfig();
    return config;
}

@Profile("!MyProfile")
@Bean(initMethod = "anotherInit", name = "MyConfig")
@ConfigurationProperties(prefix = "config")
public SomeOtherProfileConfig myConfig() {
    SomeOtherProfileConfig config = new SomeOtherProfileConfig();
    return config;
}

You should do like this

I'd combine the two @Bean methods into one and use the Environment to check the value of the spring.datasource.hikari.refresh property and then set the Hikari system property as needed .

source: https://github.com/spring-projects/spring-boot/issues/6781#issuecomment-857624340

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM