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

一、

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,而是指明特性

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

1 @Bean
2 @Qualifier("cold")
3 public Dessert iceCream() {
4     return new IceCream();
5 }

注入

@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;
}

 

转载于:https://www.cnblogs.com/shamgod/p/5235783.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值