方式一,放在構造方法上使用
代碼示例
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;