juventus juventus - 9 days ago 5
Java Question

Spring Boot Configure and Use Two DataSources

I am new to Spring and Spring Boot. How would one go about to configure and use two data sources. I am looking for more than what is no this doc page http://docs.spring.io/spring-boot/docs/1.2.3.BUILD-SNAPSHOT/reference/htmlsingle/#howto-configure-a-datasource

For example here is what I have for the first data source.

application.properties

#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver

#second db ...


Application class

@SpringBootApplication
public class SampleApplication {
private static final Logger logger = LoggerFactory.getLogger(SampleApplication.class);


public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}

@Autowired
SampleRepository repo;

@PostConstruct
public void testDriving(){
logger.debug(repo.findSomeSample("id", "other"));
}
}


How do I modify application.properties to add another data source? How do I autowire it to be used by a different repo?

Answer

Here you go

#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver

#second db ...
spring.secondDatasource.url = [url]
spring.secondDatasource.username = [username]
spring.secondDatasource.password = [password]
spring.secondDatasource.driverClassName = oracle.jdbc.OracleDriver


@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}
Comments