gpt4 book ai didi

java - 如何在spring boot中根据profile动态注入(inject)依赖

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:16 29 4
gpt4 key购买 nike

假设我有以下设置,我有一个接口(interface)有一个方法 addTaxTrans():

public interface TaxTransInterface {

Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap);

}

我有两个使用此接口(interface)实现的类。

client1 的第一个实现

@Component
public class Client1TaxImpl implements TaxTransInterface {

@Override
public Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap) {
// Common code + client 1 customization code
}
}

客户端 2 的第二次实现

@Component
public class Client2TaxImpl implements TaxTransInterface {

@Override
public Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap) {

// Common code + Client 2 customization code
}
}

下面是服务实现,这里我已经 Autowiring 了 TaxTransInterface 并调用了 addTaxtrans 方法:

@Service
public class TaxSerImpl implements TaxSer {

@Autowired
private TaxTransInterface taxTransInterface;

@Override
@Transactional(rollbackFor = Exception.class)
public Response<Map<String, Object>> addTax(TaxReq taxReq) {

// Calling Trans Function
return taxTransInterface.addTaxTrans(taxReq.getSessionId(),
taxReq.getTaxMap());
}
}

截至目前,我无法运行出现以下错误的项目:

Field taxTransInterface required a single bean, but 2 were found:

我知道这个错误是因为我对接口(interface) TaxTransInterface

有两个实现

当我通过以下命令为配置文件 client1 运行应用程序时,我们是否有动态选项:

java -jar -Dspring.profiles.active=client1 sbill-0.0.1-SNAPSHOT.war

然后动态 Client1TaxImpl 应该被注入(inject),当为 client2 运行应用程序时,Client2TaxImpl 应该被注入(inject)。

有什么建议吗?

提前致谢。

最佳答案

使用 @Profile("profilename") 注释您的 @Component 类,以便根据配置文件注入(inject)组件。

关于java - 如何在spring boot中根据profile动态注入(inject)依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754462/

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