🚀 Want to Master Spring & Java Development?
Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!
🔔 Subscribe to YouTube Channel@Autowired vs. @Resource: Key Differences in Spring Framework
Dependency Injection in Spring can be configured using annotations, with @Autowired and @Resource being two of the most common options. While both annotations inject dependencies into your Spring beans, they originate from different specifications and follow distinct resolution strategies.
1. Origin and Specification
The primary difference lies in where each annotation is defined:
- @Autowired: Belongs to the Spring Framework directly (
org.springframework.beans.factory.annotation.Autowired). It is Spring-specific and tightly couples your code to the Spring runtime. - @Resource: Belongs to the Java standard specification (JSR-250) under
javax.annotation.Resource(orjakarta.annotation.Resourcein modern Jakarta EE). It is vendor-neutral and recognized across multiple Java EE / Jakarta EE containers.
2. Resolution Mechanism: By Type vs. By Name
How Spring locates and matches beans differs significantly between the two:
- @Autowired (Default: By Type): Resolves dependencies primarily by matching the target data type. If multiple candidate beans of the same type exist, it throws a
NoUniqueBeanDefinitionExceptionunless paired with the@Qualifierannotation to narrow down the target bean by name. - @Resource (Default: By Name): Resolves dependencies primarily by bean name. It inspects the
nameattribute (e.g.,@Resource(name = "beanName")), defaulting to the field or property name if omitted. If no bean matches that name, it falls back to resolution by type.
3. Injection Target Support
Both annotations support standard dependency injection targets with slight distinctions:
- @Autowired: Can be applied to fields, setter methods, arbitrary configuration methods, and class constructors.
- @Resource: Can be applied to fields and setter methods, but cannot be applied directly to constructors.
4. Practical Summary & Best Practices
When choosing between them in Spring development:
- Use @Autowired (or prefer constructor injection) when building standard Spring applications where injection by interface type is preferred.
- Use @Resource when you have multiple beans implementing the same interface and want clean injection based on bean names without adding extra qualifier annotations.
📺 Explore More Spring Framework Tutorials
Continue expanding your Java and Spring knowledge with these related tutorials from our channel:
Click here to watch on Youtube:
https://www.youtube.com/watch?v=tkPX9T6aM9w&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| Difference between @Autowired and @Resource in Spring | Spring Tutorial | Spring Framework |
No comments:
Post a Comment