Spring中@Autowire与@Resource的区别

 

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

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

Java代码   收藏代码
  1. public class SimpleMovieLister {    
  2.     
  3.   private MovieFinder movieFinder;    
  4.     
  5.   @Resource(name="myMovieFinder")    
  6.   public void setMovieFinder(MovieFinder movieFinder) {    
  7.       this.movieFinder = movieFinder;    
  8.   }    
  9.    
  10.   @Autowire  
  11.   @Qualifer("myMovieFinder")  
  12.   public void setMovieFinder(MovieFinder movieFinder) {    
  13.       this.movieFinder = movieFinder;    
  14.   }    
  15.   
  16. }   

@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进行配合

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

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

Java代码   收藏代码
  1. public class SimpleMovieLister {    
  2.     
  3.   private MovieFinder movieFinder;    
  4.     
  5.   @Resource(name="myMovieFinder")    
  6.   public void setMovieFinder(MovieFinder movieFinder) {    
  7.       this.movieFinder = movieFinder;    
  8.   }    
  9.    
  10.   @Autowire  
  11.   @Qualifer("myMovieFinder")  
  12.   public void setMovieFinder(MovieFinder movieFinder) {    
  13.       this.movieFinder = movieFinder;    
  14.   }    
  15.   
  16. }   

@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进行配合

猜你喜欢

转载自sunbin.iteye.com/blog/2285857
今日推荐