Spring——@Autowired註解使用說明

方式一,放在構造方法上使用

代碼示例

private StudentService studentService;
@Autowired
public StudentDemoService(StudentService studentService){
    this.studentService = studentService;
}

 注意:當類中只有一個構造方法是可以省略@Autowired註解,但是有多個構造方法的時候,必須在多個構造方法中的其中一個標明@Autowired註解

 

官方文檔連接

官方文檔說明截圖:

 

方式二、放在set方法上使用

private StudentService studentService;
@Autowired
public void setStudentDemoService(StudentService studentService){
      this.studentService = studentService;
}

 官網說明截圖

方式三、放在普通方法上使用

private StudentService studentService;
@Autowired
public void InjectTest(StudentService studentService){
    this.studentService = studentService;
}

  官網說明截圖

 

方式四、放在類中的屬性使用

@Autowired
private StudentService studentService;

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章