Created
August 10, 2014 06:41
-
-
Save mismatch/79f19fff6605a25a4c9c 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 {} | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BaseDataSourcePropertiesis nothing more than descendant oforg.springframework.boot.autoconfigure.jdbc.DataSourcePropertieswithgetDriverClassNamemethod overriden to make it public.