How to ensure in Spring that only one instance of DataSource is created at application startup when there are multiple?
sobes.tech AI
Answer from AI
In Spring, to ensure that only one instance of DataSource is created at application startup, the following approaches can be used:
-
Default Singleton Bean: By default, Spring creates beans with singleton scope, so if DataSource is declared as a bean, it will be the only instance.
-
Configuration via @Configuration and @Bean:
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
// Creating and configuring DataSource
return new HikariDataSource();
}
}
-
Avoid duplicate configurations: If multiple configurations create DataSource in the project, they should be combined or profiles (@Profile) should be used to activate only one.
-
Using @Primary: If there are multiple DataSource beans, one can be marked as @Primary, so Spring chooses it by default.
-
Auto-configuration check: In Spring Boot, you can disable DataSource auto-configuration if you create the bean manually to avoid creating multiple instances.
Thus, proper configuration and bean scope management ensure the creation of a single DataSource instance.