Connecting multiple databases



I would like to connect my application with 2 different databases. This is what I have tried:

public class DataSourceWilaConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.wila")
    public DataSource wila() {
        return DataSourceBuilder.create().build();
    }
}

public class DataSourceWaldConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.wald")
    public DataSource wald() {
        return DataSourceBuilder.create().build();
    }
}

And so in application.properties I have added:

spring.datasource.url=
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.username=
spring.datasource.password=

spring.wald.datasource.url=
spring.wald.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.wald.datasource.username=
spring.wald.datasource.password=

But Intellij tells me: Cannot resolve configuration property ‘spring.wald.datasource.url’

What am I doing wrong?

Answer

Instead of returning DataSource, you could return DataSourceProperties, like:

@Configuration
@EnableConfigurationProperties
public class DataSourceWaldConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.wald")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }
}

@Configuration
@EnableConfigurationProperties
public class DataSourceWilaConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.wila")
    public DataSourceProperties wila() {
        return new DataSourceProperties();
    }
}

Also, the dependency spring-boot-configuration-processor will be required.

Important: After that’s done, you should rebuild your project.



Source: stackoverflow