@Resource註解

在java代碼中使用@Autowired或@Resource註解方式進行裝配,這兩個註解的區別是:@Autowired 默認按類型裝配,@Resource默認按名稱裝配,當找不到與名稱匹配的bean纔會按類型裝配。
    @Autowired
    private PersonDao  personDao;//用於字段上
    @Autowired
    public void setOrderDao(OrderDao orderDao) {//用於屬性的setter方法上
        this.orderDao = orderDao;
    }
@Autowired註解是按類型裝配依賴對象,默認狀況下它要求依賴對象必須存在,若是容許null值,能夠設置它required屬性爲false。若是咱們想使用按名稱裝配,能夠結合@Qualifier註解一塊兒使用。以下:
    @Autowired  @Qualifier("personDaoBean")
    private PersonDao  personDao;
@Resource註解和@Autowired同樣,也能夠標註在字段或屬性的setter方法上,但它默認按名稱裝配。名稱能夠經過@Resource的name屬性指定,若是沒有指定name屬性,當註解標註在字段上,即默認取字段的名稱做爲bean名稱尋找依賴對象,當註解標註在屬性的setter方法上,即默認取屬性名做爲bean名稱尋找依賴對象。
    @Resource(name=「personDaoBean」)
    private PersonDao  personDao;//用於字段上
注意:若是沒有指定name屬性,而且按照默認的名稱仍然找不到依賴對象時, @Resource註解會回退到按類型裝配。但一旦指定了name屬性,就只能按名稱裝配了。
 
 
步驟:
(1).修改beans.xml
Java代碼 
在java代碼中使用@Autowired或@Resource註解方式進行裝配。但咱們須要在xml配置文件中配置如下信息:  
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:context="http://www.springframework.org/schema/context"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
           http://www.springframework.org/schema/context  
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
          <context:annotation-config/>  
</beans>  
 這個配置隱式註冊了多個對註釋進行解析處理的處理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
      注: @Resource註解在spring安裝目錄的lib\j2ee\common-annotations.jar
 
   <context:annotation-config/>  必不可少java

相關文章
相關標籤/搜索