gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:35:17 24 4
gpt4 key购买 nike

我正在尝试让应用程序在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com