Spring @Autowired,@Resource,@Inject

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 orderMatch 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 locationsetter 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.

参考:Wiring in Spring: @Autowired, @Resource and @Inject

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值