【问题标题】:Spring: Qualifying different types with the same nameSpring:限定具有相同名称的不同类型
【发布时间】:2019-09-12 13:19:14
【问题描述】:

我有两个要使用 spring 自动装配的类

@Component
public class Restaurant {
    @Autowired
    @Qualifier("HighClass")
    private CoffeeMaker coffeeMaker;
}

和:

public class CappuccinoMaker implements CoffeeMaker{
    @Autowired
    @Qualifier("HighClass")
    int numOfSpoons;
}

然后注入:

@Bean(name="HighClass")
@Scope("prototype")
public CoffeeMaker HighClassCoffeeMakerGenerator() {
    return new CappuccinoMaker();
}
@Bean(name="HighClass")
public int getNumOfSpoons() {
    return 3;
}

我想用“HighClass”来限定 int 和 CoffeeMaker。在 Guice 中,可以使用相同的注释来注释不同的类型并正确地注入它们。

似乎在春天这是不允许的。当我尝试注入字段时,我收到一个错误,即找不到所需的 bean。我错过了什么吗?

【问题讨论】:

标签: spring dependency-injection autowired qualifiers


【解决方案1】:

Spring 中的 Bean 名称是 unique。使用 @Profile 从多个竞争变体中挑选一个 bean。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2012-01-25
    • 1970-01-01
    相关资源
    最近更新 更多