Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的;
@Autowired默认按照类型匹配注入bean,如果有多个实现类,搭配@Qualifier(“实现类名称”)表明注入的是哪一个实现类的bean:
比如:
@Autowired
@Qualifier(“barFormatter”)
private Formatter formatter; //注入的就是barFormatter这个实现类,注意如果该实现类使用了诸如@compent(“barFormatter”)这种注解
而@Resource默认按照名称匹配注入bean,而且可以使用name作为属性来确定实际注入的bean
比如:
@Resource(name = “TestServiceImpl1”)
private TestService testService;
@Component("fooFormatter")
public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
}
@Component("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}
@Component
public class FooService {
@Autowired
private Formatter formatter;
//todo
}
如果我们尝试将 FooService
加载到我们的上下文中,Spring 框架将抛出 NoUniqueBeanDefinitionException
。这是因为 Spring 不知道要注入哪个 bean。
通过使用 @Qualifier
注解,我们可以消除需要注入哪个 bean 的问题
@Component
public class FooService {
@Autowired
@Qualifier("fooFormatter")
private Formatter formatter;
//todo
}
通过将 @Qualifier
注解与我们想要使用的特定 Spring bean 的名称一起进行装配,Spring 框架就能从多个相同类型并满足装配要求的 bean 中找到我们想要的,避免让Spring脑裂。我们需要做的是@Component或者@Bean注解中声明的value属性以确定名称。
其实我们也可以在 Formatter
实现类上使用 @Qualifier
注释,而不是在 @Component
或者 @Bean
中指定名称,也能达到相同的效果:
@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
public String format() {
return "foo";
}
}
@Component
@Qualifier("barFormatter")
public class BarFormatter implements Formatter {
public String format() {
return "bar";
}
}
@Primary 的注解,我们也可以用来发生依赖注入的歧义时决定要注入哪个 bean。当存在多个相同类型的 bean 时,此注解定义了首选项。除非另有说明,否则将使用与 @Primary 注释关联的 bean 。
我们来看一个例子:
@Bean
public Employee tomEmployee() {
return new Employee("Tom");
}
@Bean
@Primary
public Employee johnEmployee() {
return new Employee("john");
}
在此示例中,两个方法都返回相同的 Employee
类型。Spring 将注入的 bean 是方法 johnEmployee
返回的 bean。这是因为它包含 @Primary
注解。当我们想要指定默认情况下应该注入特定类型的 bean 时,此注解很有用。
如果我们在某个注入点需要另一个 bean,我们需要专门指出它。我们可以通过 @Qualifier
注解来做到这一点。例如,我们可以通过使用 @Qualifier
注释来指定我们想要使用 tomEmployee
方法返回的 bean 。
值得注意的是,如果 @Qualifier
和 @Primary
注释都存在,那么 @Qualifier
注释将具有优先权。基本上,@Primary
是定义了默认值,而 @Qualifier
则非常具体。