by BehindJava

What is the difference between @Resource, @Inject and @Autowired in Spring Framework

Home » java » What is the difference between @Resource, @Inject and @Autowired in Spring Framework

In this tutorial, we are going to learn about the difference between @Resource, @Inject and @Autowired which is a spring proprietary annotation that injects a resource by-type. @Inject does not have the required field, thus if we are unable to identify an appropriate object to inject, it will fail. If there are few implementations of an interface or a subclass, we can eliminate ambiguity by limiting the choice using the @Qualifier.

@Resource:

JSR-250-based annotation. The major distinction between @Resource and @Autowired and @Inject is the execution pathways used to identify the necessary bean to inject. Search results will be filtered by name, type, and then qualifiers by @Resource (ignored if match is found by name). @Autowired and @Inject will focus the search by type, qualifier, and name in that order.

@Inject:

This annotation indicates constructors, methods, and fields that can be used for dependency injection in Java. The @Autowired annotation from Spring can be replaced by this one almost entirely. Therefore, you might decide to utilise @Inject rather than the @Autowired annotation that is exclusive to Spring. One of the ways that @Autowired and @Inject vary is that @Autowired can utilise required=false and allow null able fields (only if required!). @Inject does not have the required field, thus if we are unable to identify an appropriate object to inject, it will fail. The benefit of the @Inject annotation is that you may ask it to inject a Provider rather than a reference directly. Lazy injection of bean references and injection of multiple instances of a bean are two features of the Provider interface. If there are few implementations of an interface or subclass, we can eliminate ambiguity by limiting the choice with the @Named annotation. The @Named annotation is very similar to the @Qualifier in Spring.

@Autowired

In contrast to @Inject and @Resource, @Autowired is a spring proprietary annotation that injects a resource by-type, that is, by the class or by the interface of the annotated field or contractor. If there are few implementations of an interface or a subclass, we can eliminate ambiguity by limiting the choice using the @Qualifier annotation. The bean name is regarded as a default qualification value for a fallback match. Despite the fact that you can use this convention to refer to certain beans by name, the core idea behind @Autowired is type-driven injection with a choice of semantic qualifiers.