【发布时间】:2016-09-14 05:39:21
【问题描述】:
我试图在我的 SpringBoot 应用程序中使用两个数据源,但无法让第二个数据源自动装配。我尝试了很多东西,但这是我最接近的:
我的 Yaml 文件:
spring:
first-datasource:
url: MyURLString1
username: User
password: Password
driver-class-name: oracle.jdbc.OracleDriver
second-datasource:
url: MyURLString2
username: User
password: Password
driver-class-name: oracle.jdbc.OracleDriver
我的应用类:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.first-datasource")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.second-datasource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
}
最后是我的 DAO:
@Repository
public class MyDao {
private static final String FIRST_SELECT = "select * from SomeTableInDB1";
private static final String SECOND_SELECT = "select * from AnotherTableInDB2";
@Autowired
private JdbcTemplate firstJdbcTemplate;
@Autowired
@Qualifier("secondDataSource")
private JdbcTemplate secondJdbcTemplate;
List<DB1Entity> getDB1Entity(Long id) {
return firstJdbcTemplate.query(FIRST_SELECT, new Object[] {id}, new BeanPropertyRowMapper(DB1Entity.class));
}
List<DB2Entity> getDB2Entity(Long id) {
return secondJdbcTemplate.query(SECOND_SELECT, new Object[] {id}, new BeanPropertyRowMapper(DB2Entity.class));
}
}
这是迄今为止我最接近的一次。我说它是最接近的,因为如果我删除了@Qualifier,那么我的两个 dao 方法实际上都可以工作,假设 SECOND_SELECT 语句对于我的 DB1 是有效的 SQL。一旦我为我的非主要数据源输入了@Qualifier,我就会收到一个自动装配错误,因为 Spring 需要一个 Datasouce 对象,而不是 JdbcTemplate 对象。这对我来说很奇怪,因为它确实适用于主数据源。
这是我的错误:
无法自动装配字段:private org.springframework.jdbc.core.JdbcTemplate org.my.classpath.secondJdbcTemplate;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: 预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=secondDataSource)}
【问题讨论】:
-
您创建类型为 DataSource 但 Autowire JdbcTemplate 的 bean。你可能应该有这样的东西
private JdbcTemplate jdbcTemplate1; private JdbcTemplate jdbcTemplate2; @Autowired @Qualifier("firstDataSource") public void setDataSource(DataSource dataSource) { this.jdbcTemplate1 = new JdbcTemplate(dataSource); } @Autowired @Qualifier("secondDataSource") public void setDataSource(DataSource dataSource) { this.jdbcTemplate2 = new JdbcTemplate(dataSource); } -
我曾尝试过与此几乎相同的方法,但收到有关空 URL 的错误。我一定是打错了东西,因为我复制了你的代码并且它有效。谢谢。我敢肯定这很愚蠢。
-
@lenach87 这是正确的解决方案,我认为这个问题很好。发表一个答案,我会将其标记为正确的。
-
我很高兴它有帮助!我会把它作为答案发布,谢谢
标签: spring-boot datasource spring-jdbc