同一个接口,有几种不同的实现类Bean,使用@Primary标注的实现类Bean可以被优先获取;
以下是@Primary注解的使用示例:
@Configuration public class MovieConfiguration { @Bean @Primary public MovieCatalog firstMovieCatalog() { ... } @Bean public MovieCatalog secondMovieCatalog() { ... } // ... } public class MovieRecommender { @Autowired private MovieCatalog movieCatalog; // ... }MovieRecommender中注入的将会是firstMovieCatalogBean对象。
同样,也可以使用xml的方式指定Bean的primary属性,如下所示:
<?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/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean class="example.SimpleMovieCatalog" primary="true"> <!-- inject any dependencies required by this bean --> </bean> <bean class="example.SimpleMovieCatalog"> <!-- inject any dependencies required by this bean --> </bean> <bean id="movieRecommender" class="example.MovieRecommender"/> </beans>同一个接口,有几种不同的实现类Bean,其他类在引用时如果没有唯一指定(@Primary或者@Qualifier都可以进行唯一指定),那么将会产生NoUniqueBeanDefinitionException异常。
参考
https://docs.spring.io/spring-framework/docs/4.3.29.RELEASE/spring-framework-reference/htmlsingle/#beans-autowired-annotation-primary