SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除BEAN自动装配的歧义@QUALIFIER及自定义注解

时间:2023-07-11 19:57:50

一、

The @Qualifier annotation is the main way to work with qualifiers. It can be
applied alongside @Autowired or @Inject at the point of injection to specify which
bean you want to be injected. For example, let’s say you want to ensure that the
IceCream bean is injected into setDessert() :

@Autowired
@Qualifier("iceCream")
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}

id为“iceCream”的bean会被注入

二、

以id为筛选条件,则万一类名一更改,则此自动装配会失效(@componet默认是以类名首字母小写为bean的id),另一相对的较好的做好是在bean的定义端也写@Qualifier,但不是指明id,而是指明特性

 @Component
@Qualifier("cold")
public class IceCream implements Dessert { ... }

 @Bean
@Qualifier("cold")
public Dessert iceCream() {
return new IceCream();
}

注入

@Autowired
@Qualifier("cold")
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}

三、

但上述的例子,有多个合适的bean都标明@Qualifier("cold")时,还是会产生歧义,此时要自定义注解来解决

1.

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Cold { }

2.

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Creamy { }

Now you can revisit IceCream and annotate it with @Cold and @Creamy , like this:

@Component
@Cold
@Creamy
public class IceCream implements Dessert { ... }
Similarly, the Popsicle class can be annotated with @Cold and @Fruity

Similarly, the Popsicle class can be annotated with @Cold and @Fruity :

@Component
@Cold
@Fruity
public class Popsicle implements Dessert { ... }

Finally, at the injection point, you can use any combination of qualifier annotations

necessary to narrow the selection to the one bean that meets your specifications. To
arrive at the IceCream bean, the setDessert() method can be annotated like this:

@Autowired
@Cold
@Creamy
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}