Spring Boot配置和使用两个DataSource [英] Spring Boot Configure and Use Two DataSources

查看:409
本文介绍了Spring Boot配置和使用两个DataSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring和Spring Boot的新手。如何配置和使用两个数据源。

I am new to Spring and Spring Boot. How would one go about to configure and use two data sources.

例如,这是第一个数据源的内容。

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 ...

申请类

@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"));
    }
}

如何修改application.properties以添加其他数据资源?如何将其自动装配以供其他仓库使用?

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

推荐答案

此处你去了

#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();
}

这篇关于Spring Boot配置和使用两个DataSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆