sPRing2.5提供了基于注解(Annotation-based)的配置,我們可以通過注解的方式來完成注入依賴。在java代碼中可以使用 @Resource或者@Autowired注解方式來經行注入。雖然@Resource和@Autowired都可以來完成注入依賴,但它們之間是有區別的。首先來看一下:
a。@Resource默認是按照名稱來裝配注入的,只有當找不到與名稱匹配的bean才會按照類型來裝配注入; b。@Autowired默認是按照類型裝配注入的,如果想按照名稱來轉配注入,則需要結合@Qualifier一起使用; c。@Resource注解是又J2EE提供,而@Autowired是由spring提供,故減少系統對spring的依賴建議使用 @Resource的方式; d。 @Resource和@Autowired都可以書寫標注在字段或者該字段的setter方法之上
使用注解的方式,我們需要修改spring配置文件的頭信息,一般都是appcontext-*.xml之類,如下
<?xml version="1.0" encoding="UTF-8"?><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.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><context:annotation-config/></beans>修改以上配置文件的頭信息后,我們就可以在Java代碼通過注解方式來注入bean,看下面代碼
@Resource(name="studentDao")// 通過此注解完成從spring配置文件中查找名稱為studentDao的bean來裝配字段studentDao,如果spring配置文件中不存在 studentDao名稱的bean則轉向按照bean類型經行查找
配置文件添加如下信息
<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean><bean id="studentService3" class="com.wch.service.impl.StudentService3" />@Autowired//通過此注解完成從spring配置文件中 查找滿足studentDao類型的bean
//@Qualifier("studentDao")則按照名稱經行來查找轉配的 public void setStudentDao(IStudentDao studentDao) {this.studentDao = studentDao;}public void saveStudent() {studentDao.saveStudent();System.out.print(",ID 為:"+id);}}配置文件添加如下信息
<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean><bean id="studentService3" class="com.wch.service.impl.StudentService3" />在java代碼中可以使用@Autowire或者@Resource注解方式進行裝配,這兩個注解的區別是: @Autowired 默認按照類型裝配,默認情況下它要求依賴對象必須存在如果允許為null,可以設置它required屬性為false,如果我們想使用按照名稱裝配,可以結合@Qualifier注解一起使用;
@Resource默認按照名稱裝配,當找不到與名稱匹配的bean才會按照類型裝配,可以通過name屬性指定,如果沒有指定name屬 性,當注解標注在字段上,即默認取字段的名稱作為bean名稱尋找依賴對象,當注解標注在屬性的setter方法上,即默認取屬性名作為bean名稱尋找 依賴對象. 注意:如果沒有指定name屬性,并且按照默認的名稱仍然找不到依賴的對象時候,會回退到按照類型裝配,但一旦指定了name屬性,就只能按照名稱裝配了.
參考: http://blog.csdn.net/baple/article/details/17891755
新聞熱點
疑難解答