在第二章中,我们使用自动装配让spring来负责将Bean引用注入到构造参数和属性中。自动装配能够提供很大的帮助。
但是仅有一个Bean匹配所需的结果时,自动装配才是有效的。
以下例子:
@Component
public class Menu {
public Dessert dessert;
@Autowired
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}
}
@Component
public class Cake implements Dessert{
}
@Component
public class Cookies implements Dessert{
}
@Component
public class IceCream implements Dessert{
}
在这个菜单上我们需要注入一个甜品,但是我们现在有很多不止一个类实现了甜品这个接口,并且都被注册为了component。
这个时候装配Menu的时候,就会有问题。
No qualifying bean of type 'dessert.Dessert' available: expected single matching bean but found 3: cake,cookies,iceCream
二月 15, 2021 2:02:36 下午 org.springframework.test.context.TestContextManager prepareTestInstance
Spring无法做出选择,就会抛异常。
两种解决方案,primary/ qualifier
Primary
@Component
@Primary
public class Cake implements Dessert{
}
我们可以在声明Bean的时候,在@Component/@Bean的地方加上primary注解,这样出现歧义性的时候我们就会先选择这个。(cake) 注意这个primary只能在一个bean上声明,不能选择多个primary!!!!
Qualifier
使用primary有局限性,首选bean超过一个的时候就无法起效,我们不能够进一步缩小范围。(不知道书上写得啥。。)
这个注解可以与@autowired协同使用,在注入的时候指定想要注入进去的是哪个bean。所有加了component的bean的id都是类名的第一个字母小写。
@Component
public class Menu {
public Dessert dessert;
@Autowired
@Qualifier("iceCream")
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}
}
这样写很简单, 但是也有一点问题,就是如果你想要重构iceCream类,命名为Gelato,这样自动装配就会失效,你就找不到了。这里@Qualifier上面指定的限定符和bean的名称是紧耦合的!!
创建自定义的限定符号
@Component
@Qualifier("cold")
public class IceCream implements Dessert{
}
通过将icecream使用一个限定符限制了,这样重构完了之后只要不改动这个名字,就可以。
使用自定义的限定符注解
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Cold {
}
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Creamy {
}
当我们想要新的引入一种冷的甜品时,我们就会发现无法再使用cold来限定,那么我们想要加一个限定符,比如 @Qulifer("cold“)@Qualifier("creamy")来描述这个Bean,但是这样子并不行,因为一个注解不能用两次,那么。我们就使用自定义的注解,如上所示。
@Component
@Cold
@Creamy
public class IceCream implements Dessert{
}
@Component
public class Menu {
public Dessert dessert;
@Autowired
@Cold
@Creamy
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}
}
通过双重自定义限定符,我们就可以找到iceCream。通过使用自定义限定符,不会再有Java编译的问题,比较安全。
当Spring中存在多个相同类型的Bean时,自动装配可能导致歧义。本文介绍了如何通过`@Primary`和`@Qualifier`解决这个问题。`@Primary`用于指定默认首选Bean,但只能设置一个;`@Qualifier`允许指定具体Bean的名称,避免耦合于类名。此外,还讨论了创建自定义限定符注解的方法,以应对更复杂的情况。
265

被折叠的 条评论
为什么被折叠?



