简体   繁体   English

Spring嵌套的自动装配泛型抛出NoUniqueBeanDefinitionException

[英]Spring nested autowiring of generic throws NoUniqueBeanDefinitionException

Is it possible to autowire a generic type into a different generic type in the constructor? 是否可以在构造函数中将泛型类型自动装配为其他泛型类型? I currently have a structure like this: 我目前有这样的结构:

@Service
public class ExampleService {
@Autowired
ServiceA<Integer> servicea;

}

and the services: 和服务:

@Component
@Scope(SCOPE_PROTOTYPE)
public class ServiceA<S> {
  private final ServiceB<S,String> dependentServiceB;

  public ServiceA (ServiceB<S,String> dependentServiceB){
     this.dependentServiceB = dependentServiceB;
  }
}

@Configuration
public class ServiceBConfig {
  @Bean
  ServiceB<Integer,String> serviceBwithInt (){
      return new ServiceBImplInt();
  }

  @Bean
  ServiceB<Long,String> serviceBwithLong (){
      return new ServiceBImplLong();
  }

}

Now if I try to autowire the ExampleService class somewhere else, it throws a NoUniqueBeanDefinitionException containing "No qualifying bean of type '....ServiceB< ? >' available: expected single matching bean but found 2: serviceBwithInt ,serviceBwithLong". 现在,如果我尝试在其他地方自动连接ExampleService类,它将引发NoUniqueBeanDefinitionException,其中包含“没有可用类型'.... ServiceB <?>'的合格bean:预期的单个匹配bean,但发现2:serviceBwithInt,serviceBwithLong”。

Is this possible to solve it like this or do I have to implement subclasses of ServiceA for each of the different generic types? 是否可以这样解决呢?还是我必须为每个不同的泛型类型实现ServiceA的子类?

Given how type erasure works, both of those beans are eligible to be injected simply because Java would accept both of those as valid arguments to the constructor. 考虑到类型擦除的工作原理,这两个bean都有资格被注入,因为Java将接受这两个bean作为构造函数的有效参数。

If you want to be explicit about which is injected, use a @Qualifier . 如果您想明确指出要注入的对象,请使用@Qualifier

@Component
@Scope(SCOPE_PROTOTYPE)
public class ServiceA<S> {
  private final ServiceB<S,String> dependentServiceB;

  public ServiceA (@Qualifier("serviceBWithInt")ServiceB<S,String> dependentServiceB){
     this.dependentServiceB = dependentServiceB;
  }
}

If you can't be explicit about which bean you want, you may want to reconsider adding generics here. 如果您不能明确确定要使用哪个bean,则可能需要重新考虑在此处添加泛型。 There are niche reasons to want to do this in the first place, and the flow of dependency injection is still wholly predictable, even if you don't control the lifecycle of the objects. 首先有很多利基原因想要这样做,即使您不控制对象的生命周期,依赖项注入的流程仍然是完全可预测的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM