春季启动:错误注入多个bean

时间:2019-09-17 18:44:00

标签: java spring spring-boot

我正在尝试让应用程序在Spring-boot中运行,但是遇到注入错误。我有一个带有几个@Autowire类的@Service。我需要使用public setDatSource方法来对我们刚刚的POJO进行分类,我需要通过运行时来设置DataSource。见下文:

    @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无关。我想念的是什么,我呆了一段时间,觉得自己做的事很愚蠢。

3 个答案:

答案 0 :(得分:1)

您在@Bean类中的以下方法上有OnlineWsApplication注释吗?

  • createAuthReadDataSoure
  • createOnlineDSReadDataSoure
  • createOnlineDSWriteDataSoure

如果是,请摆脱它们。

OnlineWsApplication的完整代码对于调查它非常有用。

答案 1 :(得分:1)

在定义bean时,您需要指定名称,而不是限定符,在自动装配的位置应使用限定符注释:

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

    return ds;
}

答案 2 :(得分:1)

在bean定义中,而不是     @豆角,扁豆     @Qualifier(“ datasetDao”)

尝试使用以下内容:     @Bean(name =“ datasetDao”)