@qualifier和@primary小记

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

图一:

图片

图二:

图片
做为正常人只能先去看一下是否能够删除其中一个jar包,发现这条路是走不通的只能去排除其中一个Bean了
这个就要讲到今天要说的两个注解了 @Qualifier  和 @Primaryapp

@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注入ide

相关文章
相关标签/搜索