Home >Java >javaTutorial >@Resource vs @Autowired: When to Choose Which Dependency Injection Annotation?
@Resource vs @Autowired: A Deeper Dive
In the realm of dependency injection (DI), annotations play a crucial role in establishing relationships between objects. Two widely used annotations are @Resource (from JSR-250) and @Autowired (from the Spring framework). But which annotation should you choose?
@Resource: Name-Based Retrieval
@Resource serves as a mechanism to retrieve a resource by its name. This name can be specified through the "name" parameter of the annotation or inferred from the annotated field or setter's name. By utilizing @Resource, you explicitly request a known resource by its specific identifier.
@Autowired: Type-Based Wiring
On the other hand, @Autowired (or @Inject in Java EE) attempts to wire in a component that matches the required type. It does this by examining the type of the annotated field or setter and searching the application context for a compatible bean. The @Qualifier annotation can be used alongside @Autowired to narrow down the search to specific bean names, if desired.
Conceptual Differences
The fundamental distinction between @Resource and @Autowired lies in their approaches:
Spring's @Resource Behavior
While the JSR-250 specification for @Resource prioritizes name-based retrieval, Spring's implementation of @Resource includes a fallback mechanism. If name-based resolution fails, it defaults to type-based resolution similar to @Autowired. This convenience feature can lead to confusion, as developers may inadvertently use @Resource for type-based autowiring.
The above is the detailed content of @Resource vs @Autowired: When to Choose Which Dependency Injection Annotation?. For more information, please follow other related articles on the PHP Chinese website!