When building microservices with Spring Boot we often need to connect to multiple databases. To simplify this process we can use the @Configuration annotation to define a separate configuration class for our database connections. For example we can create a class called DatabaseConfig that defines a bean for our PostgreSQL database connection.
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url("jdbc:postgresql://localhost:5432/mydb")
.username("myuser")
.password("mypassword")
.build();
}
}
This way we can easily manage our database connections and switch between different databases if needed. We can also use this configuration class to define multiple data sources for different databases.
Top comments (0)