为什么可以使用@Resource,但不推荐使用@Autowired
创始人
2024-11-12 11:06:30
0

DI注入的三种方式
1、属性注入
属性注入应该是我们用的最多的一种,即通过@Autowired注解,该注解默认是按照ByType方式(按类型)注入Bean,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false)。示例代码:

@Service public class UserService {     private static User user;     // 1. Filed Injection 属性注入     @Autowired     private PlayService playService; } 

2、setter 方法注入
setter方式也会用到@Autowired注解,不过是用在成员属性的set方法上

// 2. Setter Injection setter注入 private PlayService playService; @Autowired public void setPlayService(PlayService playService) {     this.playService = playService; } 

3、构造器注入
构造器注入,则是把需要注入的对象,通过构造器来进行初始化

 	private PlayService playService; 		UserService(PlayService playService) {    		 this.playService = playService; } 
 @Component   public interface PlayService {       void play();   }    @Component   @Slf4j   public class Mp3Player implements PlayService {        @Override       public void play() {           log.info("Mp3Player play()");       }   }    @Component   @Slf4j   public class Mp4Player implements PlayService {        @Override       public void play() {           log.info("Mp4Player play()");       }   } 

区别:
1、@Resource是Java的标准注解,定义在javax.annotation.Resource包中,主要用于EJB 组件的依赖注入,但在Spring中也可以用于bean的注入。
2、@Autowired 是 Spring 框架提供的注解,定义在org.springframework.beans.factory.annotation.Autowired 包中,专门用于 Spring 环境下的依赖注入。
3、@Resource 默认按照名称进行注入,如果找不到匹配名称的 bean,则退而求其次按照类型进行注入。可以通过 name 属性指定 bean 名称,或者通过 lookup 属性指定查找方法。
4、@Autowired 默认按照类型进行注入,如果类型匹配的 bean 多于一个,则会抛出异常,除非指定了具体的 bean 名称。可以通过 required 属性来控制是否必须找到匹配的 bean。
5、IDEA推荐@Resource
(1)@Resource 是 Java 标准的一部分,因此可能被视为更通用的解决方案
(2)使用 @Resource 可以避免 Spring 的特定依赖,使得代码看起来与 Spring 解耦。 IDEA 的推荐也可能基于减少 Spring 特定的警告,例如关于字段注入的警告

相关内容

热门资讯

wepower有外挂!hhpo... wepower有外挂!hhpoker德州有挂(透视)存在挂教程(有挂猫腻)-哔哩哔哩;1、超多福利:...
wepokeai机器人!wej... wepokeai机器人!wejoker透视方法(透视)细节揭秘(确实有挂)-哔哩哔哩;亲真的是有正版...
wepokeai代打的胜率!p... wepokeai代打的胜率!pokermaster脚本(透视)黑科技教程(有挂秘笈)-哔哩哔哩是一款...
wepoke黑科技!德普之星透... wepoke黑科技!德普之星透视辅助软件是真的(透视)教你攻略(有挂方略)-哔哩哔哩是一款可以让一直...
wepoke是真的有挂!hh ... wepoke是真的有挂!hh poker辅助有用(透视)细节方法(有挂功能)-哔哩哔哩;最新版202...
wepokeai代打逻辑!po... wepokeai代打逻辑!pokemmo手机版脚本免费(透视)透明教程(真的有挂)-哔哩哔哩;是一款...
wepoke有app软件!we... wepoke有app软件!wepoker辅助工具(透视)透牌教程(有挂分析)-哔哩哔哩;wepoke...
wepok软件透明挂!哈糖大菠... 【福星临门,好运相随】;wepok软件透明挂!哈糖大菠萝软件下载(透视)2025新版教程(揭秘有挂)...
七分钟了解!新畅游互娱科技(辅... 七分钟了解!新畅游互娱科技(辅助挂)详细透视开挂辅助新2025版(切实真的有挂)-哔哩哔哩;1、首先...
wepokeai代打逻辑!德州... wepokeai代打逻辑!德州hhpoker脚本(透视)辅助教程(有挂秘笈)-哔哩哔哩;是一款可以让...