Home > other >  @ConfigurationProperties same prefix for DB on two different beans
@ConfigurationProperties same prefix for DB on two different beans

Time:11-18

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 errors 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?

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related