java - Spring-Boot:错误注入(inject)多个bean

标签 java spring spring-boot

我正在尝试让应用程序在 Spring-boot 中工作,但遇到注入(inject)错误。我有一个带有一些@Autowire 类的@Service。我们的类只是带有 public setDatSource 方法的 POJO,我需要通过运行时设置数据源。见下文:

    @Bean
    @Qualifier("datasetDao")
    public com.lexi.dao.core.DatasetDAO getDatasetDao() throws NamingException {
        DatasetDAOImpl ds = new DatasetDAOImpl();
        ds.setDataSource(createAuthReadDataSoure());

        return ds;
    }

    @Bean
    public LicenseDAO getLicenseDao() throws NamingException {
        LicenseDAOImpl ds = new LicenseDAOImpl();
        ds.setReadDataSource(createOnlineDSReadDataSoure());
        ds.setWriteDataSource(createOnlineDSWriteDataSoure());
        ds.setDistribDataSource(createAuthReadDataSoure());

        return ds;
    }

我有一个服务定义如下:

@Service
public class LicenseService {

    @Autowired
    @Qualifier("datasetDao")
    private DatasetDAO datasetDao;

    @Autowired
    private LicenseDAO licenseDao;

但是,当我运行该应用程序时,我得到以下信息:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field datasetDao in com.wk.online.services.LicenseService required a single bean, but 3 were found:
    - createAuthReadDataSoure: defined by method 'createAuthReadDataSoure' in com.wk.online.ws.OnlineWsApplication
    - createOnlineDSReadDataSoure: defined by method 'createOnlineDSReadDataSoure' in com.wk.online.ws.OnlineWsApplication
    - createOnlineDSWriteDataSoure: defined by method 'createOnlineDSWriteDataSoure' in com.wk.online.ws.OnlineWsApplication


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

我尝试添加一个@Qualifier,但这似乎与 Spring 不一致。我错过了什么,我已经这样做了一段时间,并认为我正在做一些非常愚蠢的事情。

最佳答案

定义bean时,您需要指定名称,而不是限定符,在 Autowiring 它的地方应该使用限定符注释:

@Bean(name = "datasetDao")
public com.lexi.dao.core.DatasetDAO getDatasetDao() throws NamingException {
    DatasetDAOImpl ds = new DatasetDAOImpl();
    ds.setDataSource(createAuthReadDataSoure());

    return ds;
}

关于java - Spring-Boot:错误注入(inject)多个bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980276/

相关文章:

Java:LD_LIBRARY_PATH可以访问类路径吗?

java - 如何使用 iText 将越南语文本导出为 PDF

java - ListView 不显示?

java - th :disabled objects in Thymeleaf

java - BasicHttpParams - 添加日期格式(ClassCastException)

java - SpringVaadinServlet 调用 VaadinServlet 中缺少的方法?

java - Spring 数据mongodb : How to define cursor limit in findAll method

grails - 一个组件需要一个名为 'dataSource_dbCreate' 的 bean,但找不到

linux - 如何设置 iptables 以允许 Web 流量传输到我的 Spring Boot 应用程序?

mysql - 当其他事务失败时,Spring Boot事务停止自动提交或回滚