【发布时间】:2020-10-12 13:44:12
【问题描述】:
我有一个 Java 4 和 Spring Boot 2.4.0-SNAPSHOT 应用程序。
它需要访问两个独立的数据源。我也在使用 Spring jdbc 来查询数据库。
我尝试了一个实现(见下文),但出现错误。
我有以下几点:
application.properties
# pims datasource
spring.datasource1.driver-class-name=org.postgresql.Driver
spring.datasource1.url=jdbc:postgresql://localhost:5432/pims
spring.datasource1.username=postgres
spring.datasource1.password=
spring.jpa.database-platform=postgres
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=false
# approval datasource
spring.datasource2.driver-class-name=org.postgresql.Driver
spring.datasource2.url=jdbc:postgresql://localhost:5432/approval
spring.datasource2.username=postgres
spring.datasource2.password=
和
MultipleDBConfig.java
@Configuration
@ComponentScan(basePackages = "com.nexct")
public class MultipleDBConfig {
@Bean(name = "datasource1")
@ConfigurationProperties("spring.datasource1")
@Primary
public DataSource dataSource1(){
return DataSourceBuilder.create().build();
}
@Bean(name = "datasource2")
@ConfigurationProperties("spring.datasource2")
public DataSource dataSource2(){
return DataSourceBuilder.create().build();
}
}
然后在 DAO 中,我定义了 jdbcTemplate。
CompanyContactDAOImpl.java
@Repository
public class CompanyContactDAOImpl implements CompanyContactDAO {
@Autowired
@Qualifier("datasource1") // pims datasource
private JdbcTemplate jdbcTemplate;
ApprovalRequestDAOImpl.java
@Repository
public class ApprovalRequestDAOImpl implements ApprovalRequestDAO {
@Autowired
@Qualifier("datasource2") // approval datasource
private JdbcTemplate jdbcTemplate;
现在当我启动 Spring Boot 时,出现以下错误:
无法自动接线。合格的 bean 必须是 'JdbcTemplate' 类型。
和
上下文初始化期间遇到异常 - 取消 刷新尝试: org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“approvalRequestDAOImpl”的 bean 时出错:不满意 通过字段“jdbcTemplate”表示的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 'org.springframework.jdbc.core.JdbcTemplate' 类型的限定 bean 可用:预计至少有 1 个符合 autowire 条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier("datasource2")}
和
org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“approvalRequestDAOImpl”的 bean 时出错:不满意 通过字段“jdbcTemplate”表示的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 'org.springframework.jdbc.core.JdbcTemplate' 类型的限定 bean 可用:预计至少有 1 个符合 autowire 条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier("datasource2")} 在 引起:org.springframework.beans.factory.NoSuchBeanDefinitionException:没有合格的bean 'org.springframework.jdbc.core.JdbcTemplate' 类型可用: 预计至少有 1 个 bean 有资格作为 autowire 候选者。 依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier("datasource2")}
【问题讨论】:
标签: java spring spring-boot