@Resource注解的官方解釋


一、@Resource注解的官方解釋
@Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

翻譯:@Resource,它在語義上被定義為通過其唯一的名稱來標識特定的目標組件,其中聲明的類型與匹配過程無關。

If no name is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

翻譯:如果沒有明確指定名稱,則默認名稱是從字段名稱或設置方法(get、set方法)派生的。 如果用在字段上,則采用字段名稱; 如果用在在setter方法,它采用其屬性名稱(例如getProperty()方法,取property做為屬性名稱)。

Thus in the following example, the customerPreferenceDao field first looks for a bean named customerPreferenceDao, then falls back to a primary type match for the type CustomerPreferenceDao. The “context” field is injected based on the known resolvable dependency type ApplicationContext.

解釋:customerPreferenceDao字段首先查找名字為customerPreferenceDao的bean,如果沒找到該類,則以CustomerPreferenceDao類型進行匹配。

public class MovieRecommender {
@Resource
private CustomerPreferenceDao customerPreferenceDao;
@Resource
private ApplicationContext context;

public MovieRecommender() {
}
...
}
1
2
3
4
5
6
7
8
9
10
二、比較@Resource、@Autowired
@Resource

@Resource默認按byName自動注入。
既不指定name屬性,也不指定type屬性,則自動按byName方式進行查找。如果沒有找到符合的bean,則回退為一個原始類型進行進行查找,如果找到就注入。
只是指定了@Resource注解的name,則按name后的名字去bean元素里查找有與之相等的name屬性的bean。
只指定@Resource注解的type屬性,則從上下文中找到類型匹配的唯一bean進行裝配,找不到或者找到多個,都會拋出異常。
@Autowired

@Autowired默認先按byType進行匹配,如果發現找到多個bean,則又按照byName方式進行匹配,如果還有多個,則報出異常。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM