Skip to content

Instantly share code, notes, and snippets.

@mismatch
Created August 10, 2014 06:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save mismatch/79f19fff6605a25a4c9c to your computer and use it in GitHub Desktop.
Save mismatch/79f19fff6605a25a4c9c 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 {}
}
@jamesmehorter
Copy link

Where do you get BaseDataSourceProperties from?

@mismatch
Copy link
Author

Where do you get BaseDataSourceProperties from?

BaseDataSourceProperties is nothing more than descendant of org.springframework.boot.autoconfigure.jdbc.DataSourceProperties with getDriverClassName method overriden to make it public.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment