Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @Qualifier and @Resource

Tags:

java

spring

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!

like image 705
卢声远 Shengyuan Lu Avatar asked Feb 02 '12 02:02

卢声远 Shengyuan Lu


People also ask

What is difference between @resource and @autowired?

@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.

What is the difference between @qualifier and primary?

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.

What is difference between @primary and @qualifier annotation?

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.

What is @qualifier annotation used for?

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.


1 Answers

@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.

like image 132
Ken Chan Avatar answered Oct 13 '22 04:10

Ken Chan