DEV Community

loizenai
loizenai

Posted on

@Resource Annotation in Spring

https://grokonez.com/spring-framework/resource-annotation-in-spring

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


public interface User {
    String getName();
}

public class FreeUser implements User {
    private String name;

    public FreeUser(String name) {
        System.out.println("Call constructor for FreeUser: " + name);
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

public class PremiumUser implements User{
    private String name;

    public PremiumUser(String name) {
        System.out.println("Call constructor for PremiumUser: " + name);
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

And two Beans of User:

More at:

https://grokonez.com/spring-framework/resource-annotation-in-spring

@Resource Annotation in Spring

Top comments (0)