I don’t see any difference between two ways, @Qualifier is always used with @Autowired.
@Autowired @Qualifier("alpha")
VS
@Resource(name="alpha")
Anyone could let me know the difference? Thanks!
@Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.
We use @Qualifier in Spring to autowire a specific bean among same type of beans, where as @Primary is used to give high preference to the specific bean among multiple beans of same type to inject to a bean.
The @Primary annotation sets the bean preference and it is used with the @Bean or @Component etc stereotype annotations. On the other hand, @Qualifier is usually used with @Autowired or @Inject etc annotations.
The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type. The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean . This annotation can also be applied on constructor arguments or method parameters.
@Autowired
can be used alone . If it is used alone , it will be wired by type . So problems arises if more than one bean of the same type are declared in the container as @Autowired
does not know which beans to use to inject. As a result , use @Qualifier
together with @Autowired
to clarify which beans to be actually wired by specifying the bean name (wired by name)
@Resource
is wired by name too . So if @Autowired
is used together with @Qualifier
, it is the same as the @Resource
.
The difference are that @Autowired
and @Qualifier
are the spring annotation while @Resource
is the standard java annotation (from JSR-250) . Besides , @Resource
only supports for fields and setter injection while @Autowired
supports fields , setter ,constructors and multi-argument methods injection.
It is suggested to use @Resource
for fields and setter injection. Stick with @Qualifier
and @Autowired
for constructor or a multi-argument method injection.
See this:
If you intend to express annotation-driven injection by name, do not primarily use @Autowired - even if is technically capable of referring to a bean name through @Qualifier values. Instead, prefer the JSR-250 @Resource annotation which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With