Spring中@Autowire与@Resource的区别

在@Autowire使用时,默认使用by-Type的方式进行注入

而@Resource,默认使用by-Type的方式注入,但使用by-Name方式时,相比@Autowire较方便

public class SimpleMovieLister {  
  
  private MovieFinder movieFinder;  
  
  @Resource(name="myMovieFinder")  
  public void setMovieFinder(MovieFinder movieFinder) {  
      this.movieFinder = movieFinder;  
  }  
 
  @Autowire
  @Qualifer("myMovieFinder")
  public void setMovieFinder(MovieFinder movieFinder) {  
      this.movieFinder = movieFinder;  
  }  

} 

 

 

@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

 

@Autowire用于属性、构造器、多参数方法注入,可以通过@Qualifer变为by-Name方式

 

@Resource则支持属性、setter方法上的使用:如果名字没有明确指定,默认名从那个字段名或者方法名中推断出。如果是字段,就获取这个字段名;如果是setter方法,其获取bean的属性名。

 

所以,你在注入构造器与多参数方法时,请使用@Autowire与@Qualifer进行配合

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值