@Resource, @Autowired, and @Inject annotations. All three annotations are used for dependency injection in Spring applications. The @Resource and @Inject annotations are part of the Java specification, whereas the @Autowired annotation is provided by the 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
- @Resource
Let's discuss the execution flow of each annotation with an example.
public interface Notification {
// some methods
}
import org.springframework.stereotype.Component; @Component public class Email implements Notification { // some methods }
import org.springframework.stereotype.Component;
@Component
public class SMS implements Notification {
// some methods
}
@Resource @Qualifier("invalid") private Notification email; @Autowired @Qualifier("invalid") private Notification email; @Inject @Qualifier("invalid") private Notification email;
When we execute the above code, the @Resource annotation works without any errors. However, the @Autowired and @Inject annotations fail and throw an exception, as shown below.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.prj.basics.notification.Notification]
@Resource annotation performs dependency injection by matching the field name. In this example, it finds the bean named email and injects it successfully. However, the @Autowired and @Inject annotations resolve dependencies by type first and then use the qualifier (bean name) if one is specified. Since no bean named invalid exists, both annotations fail and throw an exception.The following code works correctly for all three annotations without any errors.
@Resource @Qualifier("email") private Notification email; @Autowired @Qualifier("email") private Notification email; @Inject @Qualifier("email") private Notification email;
@Resource private Email email; @Autowired private Email email; @Inject private Email email;
No comments:
Post a Comment