QualifierPriorityPrimary简介
在日常开发中,我们通常采用Autowired注入bean,该注解默认是根据类型来自动注入的。但有些情况比较特殊,例如同一个接口可能会有几种不同的实现类,此时如果没有特殊指定,spring将无法决定注入对应的bean,只能抛出异常。(ps:参考文章《Autowired与Resource区别》、《spring如何扫描Autowired、Value、Resource》)Qualifier、Priority、Primary简介
Qualifier:通常与Autowired搭配使用,通过指定具体的beanName来注入相应的bean。
Priority:通过比较该注解包含的数值来决定优先注入哪个bean,数值越小,越优先注入。
Primary:当自动装配时出现多个bean候选者时,添加了注解Primary的bean将优先注入。
这三个注解单独使用时基本都可以理解,但是当这三个注解同时使用时,注入bean是有一定的先后顺序的,接下来将通过代码进行演示,以加深理解。代码示例
定义接口SelectedBeanpublicinterfaceSelectedBean{voidgetBeanName();}
定义3个SelectedBean接口的实现类importorg。springframework。context。annotation。Primary;importorg。springframework。stereotype。Component;ComponentPrimary指定注解PrimarypublicclassPrimarySelectedBeanimplementsSelectedBean{OverridepublicvoidgetBeanName(){System。out。println(primarySelectedBean);}}
importorg。springframework。stereotype。Component;importjavax。annotation。Priority;ComponentPriority(1)指定注解PrioritypublicclassPriorityFirstSelectedBeanimplementsSelectedBean{OverridepublicvoidgetBeanName(){System。out。println(priorityFirstSelectedBean);}}
importorg。springframework。stereotype。Component;importjavax。annotation。Priority;ComponentPriority(2)指定注解PrioritypublicclassPrioritySecondSelectedBeanimplementsSelectedBean{OverridepublicvoidgetBeanName(){System。out。println(prioritySecondSelectedBean);}}
定义一个服务类TestSelectedBeanServiceimportorg。springframework。beans。factory。annotation。Autowired;importorg。springframework。stereotype。Component;ComponentpublicclassTestSelectedBeanService{AutowiredprivateSelectedBeanselectedBean;publicvoidgetBeanName(){selectedBean。getBeanName();}}
定义一个测试类AppConfigimportorg。springframework。context。annotation。AnnotationConfigApplicationContext;importorg。springframework。context。annotation。ComponentScan;importorg。springframework。context。annotation。Configuration;ConfigurationComponentScan(com。lr。interfaces。primary)publicclassAppConfig{publicstaticvoidmain(String〔〕args){AnnotationConfigApplicationContextcontextnewAnnotationConfigApplicationContext(AppConfig。class);TestSelectedBeanServicebeancontext。getBean(TestSelectedBeanService。class);bean。getBeanName();}}
在不同的类上添加不同的注解,以表格形式统计不同的测试结果:
注入结果
PrimarySelectedBean
PriorityFirstSelectedBean
PrioritySecondSelectedBean
结果一
Primary
Priority(1)
Priority(2)
PrimarySelectedBean
结果二
Priority(1)
Priority(2)
PriorityFirstSelectedBean
结果三
Priority(2)
Priority(1)
PrioritySecondSelectedBean
结果四
没有任何指定
报错
结果五
优先注入Qualifier指定的bean总结
经过上面的测试,可以得出以下结论,spring在注入时:
(1)第一候选bean是Qualifier指定的bean;
(2)第二候选bean是Primary指定的bean;
(3)第三候选bean是Priority数值较小的bean。