【问题标题】:How to use Multiple JdbcOperations and Multiple JdbcTemplates in SpringSpring中如何使用多个JdbcOperations和多个JdbcTemplates
【发布时间】:2016-06-17 04:57:17
【问题描述】:

我有 2 个不同的数据源,我想在同一个文件中使用它们,并使用 JdbcOperations 实现来查询它们中的每一个。这可能吗?

@Repository
public class TestRepository {

    private JdbcOperations jdbcOperations;

    @Inject
    @Qualifier("dataSource1")
    private DataSource dataSource1;

    @Inject
    @Qualifier("dataSource2")
    private DataSource dataSource2;


    @Bean
    @Qualifier("jdbcTemplate1")
    public JdbcTemplate jdbcTemplate1(@Qualifier("dataSource1") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
    }
    @Bean
    @Qualifier("jdbcTemplate2")
    public JdbcTemplate jdbcTemplate1(@Qualifier("dataSource2") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
    }

    @Inject
    public TestRepository(JdbcOperations jdbcOperations) {
    this.jdbcOperations = jdbcOperations; //HOW DO I SPECIFY WHICH JDBCTEMPLATE SHOULD BE USED FOR INITIALIZING THIS JDBCOPERATIONS
    }
}

以上是我的代码,注意 JdbcOperations 是在构造函数中初始化的。但是无法指定 jdbcOperations 应该使用 哪个 jdbcTemplate。

【问题讨论】:

    标签: spring spring-boot spring-data


    【解决方案1】:

    限定符实际上应该放在参数级别:

    public TestRepository(@Qualifier("jdbcTemplate2")JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }
    

    使用名为jdbcTemplate2的bean

    【讨论】:

    • 我试过这个并得到这个错误:请求的 bean 当前正在创建中:是否存在无法解析的循环引用?
    • 您的意思是您的Repository 既是配置类又是实际类?!你真的应该把它分成两个类。
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2017-03-15
    • 2010-11-04
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多