问题描述
我使用 Spring Boot 框架开发了两个 Web 服务,并且将它们放在同一个项目中.每个 web 服务使用不同的数据库,比如 ws1 使用 Oracle1,ws2 使用 Oracle2.我已经使用 bean 定义定义了一个 DataBaseConfig,但是当我运行该应用程序时,它始终运行一个 Web 服务(并且始终相同).
I have developed two webservices using Spring Boot framework and I have them in the same project. Each webservice use a different DB, say ws1 uses Oracle1 and ws2 uses Oracle2. I have defined a DataBaseConfig with the beans definition but when I run the app, always works one webservice ( and it's always the same ).
数据库配置
@Configuration
public class DataBaseConfig {
@Bean(name = "ora1")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();}
@Bean(name = "ora2")
@ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource sqliteDataSource() {
return DataSourceBuilder.create().build();}
@Bean(name = "clients")
@Autowired
@ConfigurationProperties(prefix = "spring.datasource")
@Qualifier("datasource")
public JdbcTemplate slaveJdbcTemplate(DataSource datasource) {
return new JdbcTemplate(datasource); }
@Bean(name = "places")
@Autowired
@Primary
@ConfigurationProperties(prefix = "spring.secondDatasource")
@Qualifier("secondDatasource")
public JdbcTemplate masterJdbcTemplate(DataSource secondDatasource) {
return new JdbcTemplate(secondDatasource);}
}
我有带有 sql 语句和定义的服务定义
I have the services definition with the sql statements and the definition
@Service
public class ClientsService {
@Autowired
@Qualifier("clients")
private JdbcTemplate jdbcTemplate;
和其他服务
@Service
public class PlacesService {
@Autowired
@Qualifier("places")
private JdbcTemplate jdbcTemplate;
然后在每个控制器中我都有de映射@RequestMapping.当我运行应用程序时,我没有任何与连接相关的错误,如果我将 Web 服务分成 2 个项目,每个项目都可以正常工作.
Then in each controller I have de mapping @RequestMapping. When I run the app I have no connection-related errors and if I separate the webservices in 2 projects, each works fine.
推荐答案
这里有一些问题,包括一些不必要的注释.见下文,注意@Qualifier 的位置和限定符名称:
You have a few things going wrong here, including some unnecessary annotations. See below, note the location of @Qualifier and the qualifier name:
@Bean(name = "clients")
public JdbcTemplate slaveJdbcTemplate(@Qualifier("ora1") DataSource datasource) {
return new JdbcTemplate(datasource);
}
@Bean(name = "places")
@Primary
public JdbcTemplate masterJdbcTemplate(@Qualifier("ora2") DataSource secondDatasource) {
return new JdbcTemplate(secondDatasource);
}
这篇关于SpringBoot web 服务多个数据源只有一个工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!