# 3.3.1　标示首选的 bean

如果你像我一样，喜欢所有类型的甜点，如蛋糕、饼干、冰激凌…… 它们都很美味。但如果只能在其中选择一种甜点的话，那你最喜欢的是哪一种呢？

在声明 bean 的时候，通过将其中一个可选的 bean 设置为首选 （primary）bean 能够避免自动装配时的歧义性。当遇到歧义性的时候，Spring 将会使用首选的 bean，而不是其他可选的 bean。实际上， 你所声明就是“最喜欢”的 bean。

假设冰激凌就是你最喜欢的甜点。在 Spring 中，可以通过 @Primary 来表达最喜欢的方案。@Primary 能够与 @Component 组合用在组件扫描的 bean 上，也可以与 @Bean 组合用在 Java 配置的 bean 声明中。比如，下面的代码展现了如何将 @Component 注解的 IceCream bean声明为首选的 bean：

{% code title="IceCream.java" %}

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

{% endcode %}

或者，如果你通过 Java 配置显式地声明 IceCream，那么 @Bean 方法应该如下所示：

{% code title="Dessert.java" %}

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

{% endcode %}

如果你使用 XML 配置 bean 的话，同样可以实现这样的功能。元素有一个 primary 属性用来指定首选的 bean：

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

不管你采用什么方式来标示首选 bean，效果都是一样的，都是告诉 Spring 在遇到歧义性的时候要选择首选的 bean。

但是，如果你标示了两个或更多的首选 bean，那么它就无法正常工作了。比如，假设 Cake 类如下所示：

```java
@Component
@Primary
public class Cake implements Dessert { ... }
```

现在，有两个首选的 Dessert bean：Cake 和 IceCream。这带来了新的歧义性问题。就像 Spring 无法从多个可选的 bean 中做出选择一 样，它也无法从多个首选的 bean 中做出选择。显然，如果不止一个 bean 被设置成了首选 bean，那实际上也就是没有首选 bean 了。

就解决歧义性问题而言，限定符是一种更为强大的机制，下面就将对其进行介绍。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://potoyang.gitbook.io/spring-in-action-v4/di-3-zhang-gao-ji-zhuang-pei/untitled-3/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
