1、Use @Resource
, @Inject
, @Autowired
annotations to dependency injection
2、These annotations provide classes with a declarative way to resolve dependencies
3、Each of these annotations can resolve dependencies either by field injection
or by setter injection
.
Discussion Summary
Scenario | @Resource | @Inject | @Autowired |
---|---|---|---|
Application-wide use of singletons through polymorphism | ❌ | ✅ | ✅ |
Fine-grained application behavior configuration through polymorphism | ✅ | ❌ | ❌ |
DI should be handled solely by the Jakarta EE platform | ✅ | ✅ | ❌ |
DI should be handled solely by the Spring Framework | ❌ | ❌ | ✅ |
precedence order | Match by Name Match by Type Match by Qualifier | Match by Type Match by Qualifier Match by Name | Match by Type Match by Qualifier Match by Name |
DI location | setter DI field DI | setter DI field DI | setter DI field DI constructors DI |
Spring @Resource
Spring @Inject
Spring @Autowired
这几个注解都在什么场景下使用?
1. Application-Wide Use of Singletons Through Polymorphism
If the design is such that application behaviors are based on implementations of an interface or an abstract class
, and these behaviors are used throughout the application
, then we can use either the @Inject
or @Autowired
annotation.
The benefit of this approach is that when we upgrade the application, or apply a patch in order to fix a bug, classes can be swapped out with minimal negative impact to the overall application behavior.
In this scenario, the primary default execution path is match-by-type
.
2. Fine-Grained(细粒的) Application Behavior Configuration Through Polymorphism
If the design is such that the application has complex behavior, each behavior is based on different interfaces/abstract classes
, and the usage of each of these implementations varies acrossthe application
, then we can use the @Resource
annotation.
In this scenario, the primary default execution path is match-by-name
.
@Resource
belong to the Java extension package: javax.annotation.Resource
.
@Inject
belong to the Java extension package: javax.inject.Inject
.
@Autowired
belongs to the org.springframework.beans.factory.annotation
.
DI Should Be Handled Solely by the Jakarta EE Platform
The choice is between the @Resource
annotation and the @Inject
annotation. We should narrow down the final decision between the two annotations based on which default execution path is required.
DI Should Be Handled Solely by the Spring Framework
The only choice is the @Autowired
annotation.