0

I am new to Spring Boot and trying to configure and access two databases using Spring JDBC. Can someone help me here? I have one local database (MySQL) and another on AWS RDS (MySQL). I have configured application.yml with two data sources, but whenever I run the application, it only connects to the last database configured in application.yml. I want to connect to both database as from one database I need to get information and process and put logs in AWS RDS. Can someone help me here?

This is my Dbconfig file

@Bean(name = "rdsDatasource")
@ConfigurationProperties("spring.datasource.rds")
public DataSource rdsDatasource() {
    return DataSourceBuilder.create().build();
}

@Bean
public NamedParameterJdbcOperations namedParameterJdbcOperations(@Qualifier("rdsDatasource") DataSource rdsDbDataSource) {
    return new NamedParameterJdbcTemplate(rdsDbDataSource);
}

application.yml

datasource:
  local:
    url: jdbc:mysql://localhost:3306/test
    username: test
    password: test
    port: 3306
  rds:
    url: jdbc:mysql://aws-rds/test
    username: test
    password: test
    port: 3306.

1 Answers1

1

You've configured your DataSource to use the properties for the RDS database, that's what @ConfigurationProperties("spring.datasource.rds") does.

Each DataSource object can only connect to one database. You should create another DataSource object with @ConfigurationProperties("spring.datasource.local") and name it something else like @Bean("localDatasource"), then you will have two different DataSource objects with connections to your two databases.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • I do not want to use localDataSource in same class/ package.. I m using it in different module/functionality/package.. how to do that ... lets say I have project which has 2 packages A and B ...inside package A all task is done using local Db and inside package B all tasks uses rds Db.. any idea how to go about that ? – Archana Panchal Dec 29 '21 at 17:15