Sobes.tech
Junior — Middle

How can you choose the data source (local or remote) when using the Spring Framework?

sobes.tech AI

Answer from AI

In Spring Framework, choosing a data source (local or remote) is usually implemented through bean configuration and profiles.

  1. Using Spring Profiles:

    • Create different profiles, such as local and remote.
    • In each profile, define the corresponding DataSource bean with the necessary connection parameters.
    • When starting the application, specify the active profile using the parameter -Dspring.profiles.active=local or remote.
  2. Configuration via application.properties or application.yml:

    • Create separate configuration files for each profile, such as application-local.properties and application-remote.properties.
    • Specify the connection parameters to the local or remote data source in them.
  3. Example:

@Configuration
@Profile("local")
public class LocalDataSourceConfig {
    @Bean
    public DataSource dataSource() {
        // Configure local DataSource
        return new HikariDataSource();
    }
}

@Configuration
@Profile("remote")
public class RemoteDataSourceConfig {
    @Bean
    public DataSource dataSource() {
        // Configure remote DataSource
        return new HikariDataSource();
    }
}

Thus, switching between local and remote data sources occurs by activating the corresponding profile without changing the code.