@qualifier和@primary小记

公司最近要将所有的项目微服务化,做成统一管理,小编负责当前项目的微服务改造工作,在接入spring-cloud的过程中不可避免的遇到一些有意思的事情,把他写下来,供诸君雅赏
遇到一个小问题Bean冲突,看下图报错信息
@qualifier和@primary小记
从词义可以看出一个地方引用的名叫metricRegistry的bean原来在两个地方都被定义成了bean

图一:

@qualifier和@primary小记

图二:

@qualifier和@primary小记
作为正常人只能先去看一下是否可以删除其中一个jar包,发现这条路是走不通的只能去排除其中一个Bean了
这个就要讲到今天要说的两个注解了 @Qualifier  和 @Primary

@qualifiel

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.这个注释可用于作为预备bean的字段或参数,也可以用在其他的自定义注释下
@Qualifier(“XXX”) Spring的Bean注入配置注解,该注解指定注入的Bean的名称,Spring框架使用byName方式寻找合格的bean,这样就消除了byType方式产生的歧义。

@Primary

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one ‘primary’ bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the {@code} element’s {@code primary} attribute
不难看出如果用primary注解其中一个bean就要优先于其他的Bean,当然这个对于这种三方jar包最好不要添加的,谁知道它会不会后期又出什么幺蛾子,只能改自己的代码了最后的方案是改成@qualifiel(“getMetricRegistry”),选取了其中一个bean注入


上一篇:自己编写 小米手机自动购买脚本 (仅供个人学习 不要商业使用)


下一篇:数据的完整性(正确性和准确性)