@Autowired
:默认情况下,@Autowired
按类型装配 Spring Bean。如果容器中有多个相同类型的 bean,则框架将抛出 NoUniqueBeanDefinitionException
, 以提示有多个满足条件的 bean 进行自动装配
@Qualifier :限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者
通过将 @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 时,此注解定义了首选项。除非另有说明,否则将使用与 @Primary
注释关联的 bean
@Bean
public Employee tomEmployee() {
return new Employee("Tom");
}
@Bean
@Primary
public Employee johnEmployee() {
return new Employee("john");
}
- 指定默认情况下应该注入特定类型的 bean 时,
@Primary
很有用。如果我们在某个注入点需要另一个 bean,我们需要专门指出它。我们可以通过@Qualifier
注解来做到这一点。 @Qualifier
和@Primary
注释都存在,那么@Qualifier
注释将具有优先权。@Primary
是定义了默认值,而@Qualifier
则非常具体。