Spring自动匹配Bean注入的机制在有多个可选的Bean存在时是不可用的,需要进一步进行相关配置明确消除多个可选Bean存在的歧义性。基于Java注解的注入可通过@Primary
或@Qualify
完成。
@Primary注解
符合@Autowired
连接的候选bean有多个,如果依赖注入只需要一个bean, 在只有其中一个bean声明了@Primary
的情况下,该bean将会被注入。
@Configuration
public class MovieConfiguration {
@Bean
@Primary
public MovieCatalog firstMovieCatalog() {
... }
@Bean
public MovieCatalog secondMovieCatalog() {
... }
// ...
}
public class MovieRecommender {
@Autowired
private MovieCatalog movieCatalog;
// ...
}
firstMovieCatalog
被注入。
xml形式的配置中,<bean>
元素的primary=true
属性提供了同样的功能。
@Qualifier注解
@Primary
只能取其一作为首要依赖被注入,而@Qualifier
提供了更细粒度的过滤,可以取其一,也可以取多个。
@Qualifier
通过其标示值参数过滤掉不符合条件的bean,缩小符合依赖注入条件的范围。
@Qualifier
用于注解注入域
public class MovieRecommender {
@Autowired
@Qualifier("main")
private MovieCatalog movieCatalog;
// ...
}
@Qualifier
也可注解单独的方法参数(包括构造器参数)
public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(@Qualifier("main")MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
定义了以下两个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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="example.SimpleMovieCatalog">
<qualifier value="main"/>