SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除bean自动装配的歧义@Primary

本文深入探讨了Spring框架中自动装配机制及其歧义处理方式,特别是通过@Primary注解来指定首选bean的方法。文章详细介绍了如何在组件扫描、Java配置和XML配置文件中使用@Primary来解决bean选择的不确定性,并通过实例展示了实践应用。

一、

假设有如下三个类实现同一个接口,则自动装配时会产生歧义

 1 @Component
 2 public class Cake implements Dessert { ... }
 3 @Component
 4 public class Cookies implements Dessert { ... }
 5 @Component
 6 public class IceCream implements Dessert { ... }
 7 
 8 @Autowired
 9 public void setDessert(Dessert dessert) {
10 this.dessert = dessert;
11 }

 

二、@Primary的3种用法

Let’s say that ice cream is your favorite dessert. You can express that favorite choice
in Spring using the @Primary annotation. @Primary can be used either alongside
@Component for beans that are component-scanned or alongside @Bean for beans
declared in Java configuration. For example, here’s how you might declare the
@Component -annotated IceCream bean as the primary choice:

1.在自动扫描

@Component
@Primary
public class IceCream implements Dessert { ... }

 

2.在java配置文件中

@Bean
@Primary
public Dessert iceCream() {
    return new IceCream();
}

3.xml配置文件

1 <bean id="iceCream"
2 class="com.desserteater.IceCream"
3 primary="true" />

 

如果有两个合适的bean都标记为@Primary,则Spring还是无法确定要装配哪个bean,这时要用@Qulifier来解决歧义

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值