天天看點

@Resource與@Autowried的差別

@Resource按名字,是JDK的,@Autowired按類型,是Spring的。

在java代碼中可以使用@Autowire或者@Resource注解方式進行裝配,

@Resource

public class StudentService3 implements IStudentService {

    //@Resource(name="studentDao")

    private IStudentDao studentDao;

    private String id;

    public void setId(String id) {

    this.id = id;

    }

@Resource(name="studentDao") // 通過此注解完成從spring配置檔案中查找名稱為studentDao的bean來裝配字段studentDao,如果spring配置檔案中不存在 studentDao名稱的bean則轉向按照bean類型經行查找

@Autowired

public class StudentService3 implements IStudentService {

  //@Autowired

  private IStudentDao studentDao;

  private String id;

  public void setId(String id) {

       this.id = id;

   }

@Autowired

//通過此注解完成從spring配置檔案中 查找滿足studentDao類型的bean

這兩個注解的差別是:

@Autowire 預設按照類型裝配,預設情況下它要求依賴對象必須存在,不存在會NullpointException,如果允許為null,可以設定它required屬性為false,如果我們想使用按照名稱裝配,可 以結合@Qualifier注解一起使用;

@Resource預設按照名稱裝配,當找不到與名稱比對的bean才會按照類型裝配,可以通過name屬性指定,如果沒有指定name屬 性,當注解标注在字段上,即預設取字段的名稱作為bean名稱尋找依賴對象,當注解标注在屬性的setter方法上,即預設取屬性名作為bean名稱尋找 依賴對象.

@Autowired字段注入會産生警告,并且建議使用構造方法注入。而使用@Resource不會有警告。

2,不建議使用字段注入和setter注入的方法,前者可能引起NullPointerException,後者不能将屬性設定為final。從spring4開始官方一直推薦使用構造方法注入。但是構造方法注入隻能使用@Autowired,不能使用@Resource。

3,綜上,如果要字段注入,使用@Resource;要構造方法注入,使用@Autowired。其實實際開發中個人覺得沒什麼差別。

繼續閱讀