Skip to content

Instantly share code, notes, and snippets.

@javajack
Forked from mismatch/DatabasesConfig.java
Last active September 9, 2015 08:23
Show Gist options
  • Save javajack/2978e371016ff1a24115 to your computer and use it in GitHub Desktop.
Save javajack/2978e371016ff1a24115 to your computer and use it in GitHub Desktop.
Spring Boot. Multiple datasources configuration example
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