因为按类型自动配置可能会导致多个候选者,所以通常有必要对选择过程进行更多的控制。实现这一目标的方法之一是使用 Spring 的 @Primary注解。@Primary表示,当多个 Bean 是自动连接到一个单值依赖关系的候选者时,应该优先考虑一个特定的 Bean。如果在候选者中正好有一个主要 Bean 存在,它就会成为自动连接的值。
考虑下面的配置,它将 firstMovieCatalog 定义为主 MovieCatalog:
@Configurationpublic class MovieConfiguration {@Bean@Primarypublic MovieCatalog firstMovieCatalog() { ... }@Beanpublic MovieCatalog secondMovieCatalog() { ... }// ...}
使用前面的配置,下面的 MovieRecommender 会自动连接到 firstMovieCatalog:
public class MovieRecommender {@Autowiredprivate MovieCatalog movieCatalog;// ...}
相应的 bean 定义如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><context:annotation-config/><bean class="example.SimpleMovieCatalog" primary="true"><!--注入此 Bean 所需的任何依赖 --></bean><bean class="example.SimpleMovieCatalog"><!-- 注入此 Bean 所需的任何依赖 --></bean><bean id="movieRecommender" class="example.MovieRecommender"/></beans>
