如何根据 spring 引导中的配置文件动态注入依赖项
How to inject dependency dynamically based on profile in spring boot
假设我有以下设置,我的一个界面有一种方法addTaxTrans()
:
public interface TaxTransInterface {
Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap);
}
我有两个 类 实现了这个接口。
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
}
}
下面是服务实现,这里我自动装配了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:
我知道这个错误是因为我有两个接口实现 TaxTransInterface
那么,当我通过以下命令申请配置文件 client1
:
时,我们是否有动态选项?
java -jar -Dspring.profiles.active=client1 sbill-0.0.1-SNAPSHOT.war
然后动态 Client1TaxImpl
应该注入,当 运行 申请 client2
时 Client2TaxImpl
应该注入。
有什么建议吗?
提前致谢。
用 @Profile("profilename")
注释您的 @Component
class 以便根据配置文件注入组件。
假设我有以下设置,我的一个界面有一种方法addTaxTrans()
:
public interface TaxTransInterface {
Response<Map<String, Object>> addTaxTrans(Long sessionId, TaxMap taxMap);
}
我有两个 类 实现了这个接口。
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
}
}
下面是服务实现,这里我自动装配了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:
我知道这个错误是因为我有两个接口实现 TaxTransInterface
那么,当我通过以下命令申请配置文件 client1
:
java -jar -Dspring.profiles.active=client1 sbill-0.0.1-SNAPSHOT.war
然后动态 Client1TaxImpl
应该注入,当 运行 申请 client2
时 Client2TaxImpl
应该注入。
有什么建议吗?
提前致谢。
用 @Profile("profilename")
注释您的 @Component
class 以便根据配置文件注入组件。