Difference between @Primary vs @Autowired with @Qualifier annotations

前端 未结 3 774
野性不改
野性不改 2021-01-30 22:27

So, if I understood correctly, both are the way to determine which bean to autowire if there are multiple candidates. So what exactly is the difference?

3条回答
  •  花落未央
    2021-01-30 23:23

    @Qualifier

    If there are more than one instances available for an injection point then we can use @Qualifier annotation to resolve an ambiguity. As @Qualifier is used at the injection point, there might be two situations where we don't want to or cannot use @Qualifier.

    1. When autowiring mode is Autowire.BY_TYPE. Then, of course, we cannot use @Qualifier because we actually don't have user-defined injection point specified as @Autowired or @Inject
    2. We want to do bean selection (i.e. resolve the ambiguity) at configuration time rather than during beans development time.

    The solution to above problems is to use @Primary annotation.

    @Primary

    This Indicates that a particular bean should be given preference when multiple beans are candidates to be autowired to a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

提交回复
热议问题