为了账号安全,请及时绑定邮箱和手机立即绑定

Spring-Boot:错误注入多个bean

Spring-Boot:错误注入多个bean

慕村225694 2023-08-04 15:26:50
我正在尝试让应用程序在 Spring-boot 中工作,但遇到注入错误。我有一个带有一些@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;    }我有一个服务定义如下:@Servicepublic 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.OnlineWsApplicationAction: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 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

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


@Bean(name = "datasetDao")

public com.lexi.dao.core.DatasetDAO getDatasetDao() throws NamingException {

    DatasetDAOImpl ds = new DatasetDAOImpl();

    ds.setDataSource(createAuthReadDataSoure());


    return ds;

}


查看完整回答
反对 回复 2023-08-04
?
白衣非少年

TA贡献1155条经验 获得超0个赞

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

  • createAuthReadDataSoure

  • createOnlineDSReadDataSoure

  • createOnlineDSWriteDataSoure

如果是的话,摆脱它们。

完整的代码OnlineWsApplication对于入侵它非常有用。


查看完整回答
反对 回复 2023-08-04
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

在bean定义中,用@Qualifier("datasetDao")代替@Bean

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


查看完整回答
反对 回复 2023-08-04
  • 3 回答
  • 0 关注
  • 116 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信