[英]is it possible to create multiple spring beans (from different interfaces) with the same name?
I'm trying to create the following structure:我正在尝试创建以下结构:
public interface A {string calculateA(){....}}
@Service("policy1")
public class APolicy1 implements A {
@Override
public String calculateA(){...}
}
@Service("policy2")
public class APolicy2 implements A {
@Override
public String calculateA(){...}
}
and another interface和另一个界面
public interface B{string calculateB(){....}}
@Service("policy1")
public class BPolicy1 implements B{
@Override
public String calculateB(){...}
}
@Service("policy2")
public class BPolicy2 implements B{
@Override
public String calculateB(){...}
}
and the classes that uses these beans:以及使用这些 bean 的类:
@service
@Primary
public class Arouter implements A{
@Autowired
Map<String, A> AServices;
@Autowired
PolicyResolver policyResolver;
@Override
public String calculateA(){
String policy = policyResolver.getPolicy();
AServices.get(policy).CalculateA();
}
@service
@Primary
public class Brouter Implements B{
@Autowired
Map<String, B> AServices;
@Autowired
PolicyResolver policyResolver;
@Override
public String calculateB(){
String policy = policyResolver.getPolicy();
AServices.get(policy).CalculateB();
}
note: the idea here is to delegate to the correct business logic by some kind of policy for example, if i'm running in policy a context and need to trigger Service B, then the router will call BPolicy2 method.注意:这里的想法是通过某种策略委托正确的业务逻辑,例如,如果我在策略上下文中运行并且需要触发服务 B,则路由器将调用 BPolicy2 方法。
but I'm getting:但我得到:
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'policy1' for bean class [...apackage.APolicy1] conflicts with existing, non-compatible bean definition of same name and class [...bpackage.BPolicy1]
I would expect that since these are different bean types I would be able to give them the same name我希望因为这些是不同的 bean 类型,所以我可以给它们起相同的名字
edit: I have a solution: add a prefix to the beans the name and the routers will add the prefix to the policyResolver return value, but I'm it's less elegant编辑:我有一个解决方案:在bean名称中添加前缀,路由器会将前缀添加到policyResolver返回值中,但我认为它不太优雅
@qualifier annotation can be used to differentiate between different beans. @qualifier 注解可以用来区分不同的bean。
Here is a link with small example of @qualifier annotation usage in Spring :这是一个链接,其中包含 Spring 中 @qualifier 注释用法的小示例:
https://memorynotfound.com/handling-multiple-autowire-dependencies-with-spring-qualifier/ https://memorynotfound.com/handling-multiple-autowire-dependencies-with-spring-qualifier/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.