您的位置:首页 > 其它

@qualifier和@primary小记

2021-03-04 22:53 519 查看

公司最近要将所有的项目微服务化,做成统一管理,小编负责当前项目的微服务改造工作,在接入spring-cloud的过程中不可避免的遇到一些有意思的事情,把他写下来,供诸君雅赏
遇到一个小问题Bean冲突,看下图报错信息

从词义可以看出一个地方引用的名叫metricRegistry的bean原来在两个地方都被定义成了bean

图一:

图二:


作为正常人只能先去看一下是否可以删除其中一个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注入


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: