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

时间:2021-05-05 06:19:07

一、

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

 @Component
public class Cake implements Dessert { ... }
@Component
public class Cookies implements Dessert { ... }
@Component
public class IceCream implements Dessert { ... } @Autowired
public void setDessert(Dessert dessert) {
this.dessert = dessert;
}

二、@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配置文件

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

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