我想与我的SpringBoot应用程序一起使用两个数据源,无法获得第二个数据源自动装配。我已经尝试了很多事情,但,这是我来最接近:SpringBoot和SpringJDBC多个数据源
我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();
}
}
终于吾道:
@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对象。这对我来说很奇怪,因为它与主要数据源一起工作。
这是我的错误:
无法自动装配领域:私人org.springframework.jdbc.core.JdbcTemplate org.my.classpath.secondJdbcTemplate;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到符合要求的[org.springframework.jdbc.core.JdbcTemplate]类型的合格bean:期望至少1个符合此依赖关系自动装配候选资格的bean。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true),@ org.springframework.beans.factory.annotation.Qualifier(value = secondDataSource)}
您创建DataSource类型的bean,但创建了Autowire JdbcTemplate。你可能应该有这样的'私人JdbcTemplate jdbcTemplate1; 私人JdbcTemplate jdbcTemplate2; (DataSource) @Autowired @Qualifier(“firstDataSource”) public void setDataSource(DataSource dataSource){ this.jdbcTemplate1 = new JdbcTemplate(dataSource); } @Autowired @Qualifier( “secondDataSource”) 公共无效的setDataSource(DataSource的数据源){ this.jdbcTemplate2 =新的JdbcTemplate(数据源); } ' – lenach87
我曾尝试过几乎与此相同的内容,但收到有关空URL的错误。我一定错了什么,因为我复制了你的代码并且它工作。谢谢。我相信这是愚蠢的。 – Gremash
@ lenach87这是正确的解决方案,我认为这个问题很好。发表一个答案,我会将其标记为正确的。 – Gremash