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.
-
Using Spring Profiles:
- Create different profiles, such as
localandremote. - 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=localorremote.
- Create different profiles, such as
-
Configuration via application.properties or application.yml:
- Create separate configuration files for each profile, such as
application-local.propertiesandapplication-remote.properties. - Specify the connection parameters to the local or remote data source in them.
- Create separate configuration files for each profile, such as
-
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.