@Resource Annotation in Spring


@Resource Annotation is used to indicate a reference to a resource, it is considered an alternative to @Autowired which is an Spring standard. Similar to Java EE 5, we can use @Resource Annotation with field injection or setter method.

This tutorial will cover those kinds of injection which will be used for matching by Name, Type or Qualifier.

I. Field Injection
1. By Name

We have two implementations of interface User: FreeUser and PremiumUser.

And two Beans of User:

What we need is that user1 and user2 will be injected those Beans above.

To apply Field Injection by Name, we add @Resource(name = “nameOfBean“) before the field that we wanna inject Bean to.

2. By Type

Injecting Bean to field can be done without adding name attribute, we just need @Resource before the field.

3. By Qualifier

We have two implementations of interface DataCenter: FreeStorage and PremiumStorage.

To apply Field Injection by Qualifier with these Beans and fields:

We add @Resource and @Qualifier(“…”) before fields as below:

II. Setter Method

Instead of using @Resource annotations before fields, we can apply them with setter methods.

1. By Name

2. By Type

3. By Qualifier

III. Source code
1. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

2. Project Structure


3. Download Link


4. Check results

– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:

By grokonez | November 3, 2016.

Last updated on September 25, 2018.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *