-
-
Save mandanai/8e5578a0fb8183b84f38 to your computer and use it in GitHub Desktop.
Spring Boot. Multiple datasources configuration example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.sql.DataSource; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.beans.factory.annotation.Qualifier; | |
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; | |
import org.springframework.boot.context.properties.ConfigurationProperties; | |
import org.springframework.boot.context.properties.EnableConfigurationProperties; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
@Configuration | |
@EnableConfigurationProperties({ | |
DatabasesConfig.DataSourceOneProperties.class, | |
DatabasesConfig.DataSourceTwoProperties.class}) | |
public class DatabasesConfig { | |
@Autowired | |
DataSourceOneProperties dsOneProperties; | |
@Autowired | |
DataSourceTwoProperties dsTwoProperties; | |
@Bean @Qualifier("ds_one") | |
public DataSource dataSourceOne() { | |
return createDataSource(dsOneProperties); | |
} | |
@Bean @Qualifier("ds_two") | |
public DataSource dataSourceTwo() { | |
return createDataSource(dsTwoProperties); | |
} | |
private DataSource createDataSource(BaseDataSourceProperties properties) { | |
DataSourceBuilder factory = DataSourceBuilder | |
.create(properties.getClassLoader()) | |
.driverClassName(properties.getDriverClassName()) | |
.url(properties.getUrl()) | |
.username(properties.getUsername()) | |
.password(properties.getPassword()); | |
return factory.build(); | |
} | |
@ConfigurationProperties(prefix = "appName.dbOne.datasource") | |
static class DataSourceOneProperties extends BaseDataSourceProperties {} | |
@ConfigurationProperties(prefix = "appName.dbTwo.datasource") | |
static class DataSourceTwoProperties extends BaseDataSourceProperties {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment