gpt4 book ai didi

java - 在这种情况下,如何使 spring 在使用泛型时注入(inject)正确的 bean?

转载 作者:太空宇宙 更新时间:2023-11-04 09:35:24 25 4
gpt4 key购买 nike

我有以下测试:

@SpringJUnitConfig(SpringContextTest.Foo.class)
public class SpringContextTest {

@Autowired
private Predicate<Double> predicate;

@Configuration
public static class Foo {

@Bean
@Scope("prototype")
public <T extends Number> Predicate<T> numberPredicate() {
return t -> true;
}

@Bean
@Scope("prototype")
public <T extends CharSequence> Predicate<T> charSequencePredicate() {
return t -> true;
}
}

@Test
public void foo() {
}
}

我想将 numberPredicate 的 bean 实例注入(inject)到 SpringContextTest.predicate。然而测试会导致错误:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying 
bean of type 'java.util.function.Predicate<java.lang.Double>' available: expected
single matching bean but found 2: numberPredicate,charSequencePredicate

@Bean方法和@Scope("prototype")上使用类型参数的原因是我认为spring将能够实例化不同的bean并根据要注入(inject)的字段中使用的类型参数相应地注册它们。

我知道如果我将 predicate 的声明替换为

,上述测试就会有效
    @Autowired
private Predicate<? super Double> predicate;

但这给使用该 bean 的客户端带来了负担,因此我想避免这种情况。

我还想避免使用 @Qualifier("numberPredicate") 来不依赖于 bean 名称。

那么有没有办法将正确的bean注入(inject)到字段谓词中?

最佳答案

有界通配符或 @Qualifier 非常适合这种情况,但是,正如您所说,您不喜欢依赖 bean 名称,您可以使用 @Primary 注释来指示首选 bean,或者使用 Autowiring 所有 Autowiring 候选者的列表

@Autowired
private List<Predicate<Double>> predicate;

并在类构造函数或@PostConstruct方法中手动选择您喜欢的bean。

关于java - 在这种情况下,如何使 spring 在使用泛型时注入(inject)正确的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56578054/

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