spring2.5提供了基於注解(Annotation-based)的配置,我們可以通過注解的方式來完成注入依賴。在Java代碼中可以使用 @Resource或者@Autowired注解方式來經行注入。雖然@Resource和@Autowired都可以來完成注入依賴,但它們之間是有區 別的。首先來看一下:
- @Resource默認是按照名稱來裝配注入的,只有當找不到與名稱匹配的bean才會按照類型來裝配注入;
- @Autowired默認是按照類型裝配注入的,如果想按照名稱來轉配注入,則需要結合@Qualifier一起使用;
- @Resource注解是又J2EE提供,而@Autowired是由Spring提供,故減少系統對spring的依賴建議使用@Resource的方式;
- @Resource和@Autowired都可以書寫標注在字段或者該字段的setter方法之上。
- 使用注解的方式,我們需要修改spring配置文件的頭信息,修改部分紅色標注,如下:
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> </beans>
- 修改以上配置文件的頭信息后,我們就可以在Java代碼通過注解方式來注入bean,看下面代碼:
- @Resource
1 public class StudentService3 implements IStudentService { 2 3 //@Resource(name="studentDao")放在此處也是可行的 4 private IStudentDao studentDao; 5 private String id; 6 public void setId(String id) { 7 this.id = id; 8 } 9 10 @Resource(name="studentDao") // 通過此注解完成從spring配置文件中查找名稱為studentDao的bean來裝配字段studentDao,如果spring配置文件中不存在 studentDao名稱的bean則轉向按照bean類型經行查找 11 public void setStudentDao(IStudentDao studentDao) { 12 this.studentDao = studentDao; 13 } 14 15 public void saveStudent() { 16 studentDao.saveStudent(); 17 System.out.print(",ID 為:"+id); 18 } 19 20 }
配置文件添加如下信息 <bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean> <bean id="studentService3" class="com.wch.service.impl.StudentService3" /
- Autowired
1 public class StudentService3 implements IStudentService { 2 3 //@Autowired放在此處也是可行的 4 private IStudentDao studentDao; 5 6 7 private String id; 8 9 10 public void setId(String id) { 11 this.id = id; 12 } 13 14 @Autowired//通過此注解完成從spring配置文件中 查找滿足studentDao類型的bean 15 16 //@Qualifier("studentDao")則按照名稱經行來查找轉配的 17 public void setStudentDao(IStudentDao studentDao) { 18 this.studentDao = studentDao; 19 } 20 21 22 public void saveStudent() { 23 studentDao.saveStudent(); 24 System.out.print(",ID 為:"+id); 25 } 26 27 28 }
配置文件添加如下信息:
<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean>
<bean id="studentService3" class="com.wch.service.impl.StudentService3" />
在java代碼中可以使用@Autowire或者@Resource注解方式進行裝配,這兩個注解的區別是:
@Autowire 默認按照類型裝配,默認情況下它要求依賴對象必須存在如果允許為null,可以設置它required屬性為false,如果我們想使用按照名稱裝配,可 以結合@Qualifier注解一起使用;
@Resource默認按照名稱裝配,當找不到與名稱匹配的bean才會按照類型裝配,可以通過name屬性指定,如果沒有指定name屬 性,當注解標注在字段上,即默認取字段的名稱作為bean名稱尋找依賴對象,當注解標注在屬性的setter方法上,即默認取屬性名作為bean名稱尋找 依賴對象.
注意:如果沒有指定name屬性,並且按照默認的名稱仍然找不到依賴的對象時候,會回退到按照類型裝配,但一旦指定了name屬性,就只能按照名稱 裝配了.
