Friday 1 September 2023

Difference Between @Resource, @Autowired and @Inject in Spring Injection

         In this post, we will learn the difference between Resource, Autowired and Inject annotation. All these annotations are used to inject the bean dependencies. Resource and Inject annotations are defined in Java and Autowired annotation defined in Spring framework.

@Resource – It's defined in the javax.annotation package and it's part of java.

@Inject – It's defined in the javax.inject package and it's part of Java

@Autowired – It's defined in the package org.springframework.bean.factory and part of Spring framework.

          Internally @Inject and @Autowired annotations use the AutowiredAnnotationBeanPostProcessor to inject the dependencies. But @Resource annotation internally use CommonAnnotationBeanPostProcessor to inject the dependencies. Execution path/step is same for both Inject and Autowired annotations, Resource annotation execution paths also same but order of execution paths are not same.

  • @Inject and @Autowired
         1) Matches by Type
         2) Restricts by Qualifiers
         3) Matches by Name
  • @Resource
         1) Matches by Name
         2) Matched by Type
         3) Restricts by Qualifiers

Let us discuss with example of each Annotation execution path,

Notification.java,
public interface Notification {
    // some methods
}

Email.java,
import org.springframework.stereotype.Component;
@Component
public class Email implements Notification {
    // some methods
}

SMS.java,
import org.springframework.stereotype.Component;
@Component
public class SMS implements Notification {
    // some methods
}

Inject the above beans into the caller java class,

@Resource
@Qualifier("invalid")
private Notification email;
 
@Autowired
@Qualifier("invalid")
private Notification email;
 
@Inject
@Qualifier("invalid")
private Notification email;

when we execute above code, the @Resource annotation will work fine without any error but @Autowired and @Inject will fail and through an exception like below,

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.prj.basics.notification.Notification]

           The Resource annotation checks by field name and it found the bean definition using name i.e email and will create the bean object internally but other two annotations checks by qualifier i.e by bean name mentioned in the component and there is no bean name with invalid and throw an exception.

Below code should works for all three annotations without fail.
 
@Resource
@Qualifier("email")
private Notification email;
 
@Autowired
@Qualifier("email")
private Notification email;
 
@Inject
@Qualifier("email")
private Notification email;

OR 

@Resource
private Email email;
 
@Autowired
private Email email;
 
@Inject
private Email email;

Thank you for visiting the blog.

Reference posts:-

No comments:

Post a Comment