如何配置和使用两个数据源?
例如,这里是我的第一个数据源:
应用程序属性
#first db spring.datasource.url = [url] spring.datasource.username = [username] spring.datasource.password = [password] spring.datasource.driverClassName = oracle.jdbc.OracleDriver #second db ...
应用类
@SpringBootApplication public class SampleApplication { public static void main(String[] args) { SpringApplication.run(SampleApplication.class, args); } }
如何修改application.properties以添加另一个数据源?如何自动装配它以供不同的存储库使用?
application.properties
干得好。
添加你的 application.properties 文件:
#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
在使用 @Configuration 注释的任何类中添加以下方法:
@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(); }