@Autowired注解總結

@Autowired使用注解總結

1.使用方法

1.1 作用在構造器上

public class MovieRecommender {
 private final CustomerPreferenceDao customerPreferenceDao;
 @Autowired
 public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
 this.customerPreferenceDao = customerPreferenceDao;
 }
 // ...
}

注意:

As of Spring Framework 4.3, the @Autowired constructor is no longer necessary if the target
bean only defines one constructor. If several constructors are available, at least one must be
annotated to teach the container which one it has to use.

如果使用該注解的類有一個構造器,則 is no longer necessary ,沒有必要再單獨放置一個@Autowired注解了,Spring框架會自動幫助我們完成注入的功能。但是如果該該有多個注解 several constructors are available,這個時候我們就需要選擇一個構造函數,并標注上該注解@Autowired了。

1.2 使用在setter方法上

public class SimpleMovieLister {
 private MovieFinder movieFinder;
 @Autowired
 public void setMovieFinder(MovieFinder movieFinder) {
 this.movieFinder = movieFinder;
 }
 // ...
}

1.3 使用在域屬性上

public class MovieRecommender {
 private final CustomerPreferenceDao customerPreferenceDao;
 @Autowired
 private MovieCatalog movieCatalog;
 @Autowired
 public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
 this.customerPreferenceDao = customerPreferenceDao;
 }
 // ...
}

1.4 使用在任意方法名和參數的普通方法上

public class MovieRecommender {
 private MovieCatalog movieCatalog;
 private CustomerPreferenceDao customerPreferenceDao;
 @Autowired
 public void prepare(MovieCatalog movieCatalog,
 CustomerPreferenceDao customerPreferenceDao) {
 this.movieCatalog = movieCatalog;
 this.customerPreferenceDao = customerPreferenceDao;
 }
 // ...
}

1.5 使用在域屬性數組上

It is also possible to provide all beans of a particular type from the ApplicationContext by adding
the annotation to a field or method that expects an array of that type:

public class MovieRecommender {
 @Autowired
 private MovieCatalog[] movieCatalogs;
 // ...
}

1.6 使用在java集合類型上

public class MovieRecommender {
 private Set<MovieCatalog> movieCatalogs;
 @Autowired
 public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
 this.movieCatalogs = movieCatalogs;
 }
 // ...
}

小提示:如果當初定義的bean上有@Order注解或者標準注解@Priority的話,那么注入的集合就是有序的,這個元素順序是當初注解定義的優先順序。

Your beans can implement the org.springframework.core.Ordered interface or either use
the @Order or standard @Priority annotation if you want items in the array or list to be sorted
into a specific order.

使用在Map上

Even typed Maps can be autowired as long as the expected key type is String. The Map values will
contain all beans of the expected type, and the keys will contain the corresponding bean names:

如果注入的Map中Key為String類型,并且代表每個bean的name,value為指定的bean類型,則也可以直接注入.

public class MovieRecommender {
 private Map<String, MovieCatalog> movieCatalogs;
 @Autowired
 public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
 this.movieCatalogs = movieCatalogs;
 }
 // ...
}

1.9 使用在Spring內部的接口上

You can also use @Autowired for interfaces that are well-known resolvable
dependencies: BeanFactory, ApplicationContext, Environment, ResourceLoader,
ApplicationEventPublisher, and MessageSource. These interfaces and their extended
interfaces, such as ConfigurableApplicationContext or ResourcePatternResolver, are
automatically resolved, with no special setup necessary.

該注解同樣可以使用在BeanFactory, ApplicationContext, Environment, ResourceLoader,
ApplicationEventPublisher 這些我們都知道而且很重要的接口上。

1.8 required屬性

@Autowired’s required attribute is recommended over the `@Required
annotation. The required attribute indicates that the property is not required for autowiring purposes, the property is ignored if it cannot be autowired. @Required, on the other hand, is
stronger in that it enforces the property that was set by any means supported by the container. If
no value is injected, a corresponding exception is raised.

@Autowired注解的required屬性值可以為true和false。如果為true的話,則在進行注入的時候,如果找不到要注入的類,則會拋錯。如果為false,則表示不是強制必須能夠找到相應的類,無論是否注入成功,都不會拋錯。

另外,當利用該注解注入相應的對象(其實就是類初始化為一個對象的過程),會調用該對象的構造方法,如果該對象有多個構造方法,則Spring就會“貪心”地調用參數最多的那個構造方法。相關的官方說明如下:

Only one annotated constructor per-class can be marked as required, but multiple non-required
constructors can be annotated. In that case, each is considered among the candidates and Spring
uses the greediest constructor whose dependencies can be satisfied, that is the constructor that
has the largest number of arguments.

2.其他注入注解

  • @Inject (javax.inject JSR330 (Dependency Injection for Java))
  • @Resource (javax.annotation JSR250 (Common Annotations for Java))

這里引用參考文章的區別總結:

@Autowired和@Resource

  • autowired by type
  • 可以 通過@Qualifier 顯式指定 autowired by qualifier name(非集合類。注意:不是autowired by bean name?。?/li>
  • 如果 autowired by type 失?。ㄕ也坏交蛘哒业蕉鄠€實現),則退化為autowired by field name(非集合類)

@Resource

  • 默認 autowired by field name
  • 如果 autowired by field name失敗,會退化為 autowired by type
  • 可以 通過@Qualifier 顯式指定 autowired by qualifier name
  • 如果 autowired by qualifier name失敗,會退化為 autowired by field name。但是這時候如果 autowired by field name失敗,就不會再退化為autowired by type了。

更多具體細節參考這篇文章: Spring各種依賴注入注解的區別

說明

  1. 這篇總結中所引用的英文描述和代碼片段全部來自與Spring的官方文檔:Spring Framework Reference Documentation 4.3.3 RELEASE
  2. 參考文章:Spring各種依賴注入注解的區別
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容