前面我們把@Autowired註解在類私有變量上,實行了依賴注入。在這篇博客,我們將瞭解@Autowired的其他使用方式。
我們可以觀察@Autowired的元註解:@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})。可以發現該註解還可以註解在構造器、方法和參數變量上。
- 把@Autowired註解在構造器上:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
private Student student;
@Autowired
private StudentService(Student student){
this.student = student;
}
public void showInfo(){
System.out.println(student);
}
}
- 測試代碼:
import com.michael.annotation.demo.service.StudentService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
out.println("The container has been initialized.");
((StudentService)applicationContext.getBean("studentService")).showInfo();
out.println("The container has been destroyed.");
}
}
- 輸出:
The container has been initialized.
Student{name='Nobody', ID='A00', age=16}
The container has been destroyed.
-
我們可以看到,當@Autowired註解在構造器上,Student Bean仍被注入到了其參數上。其實如果我們把@Autowired去除也同樣有該效果。Spring默認組件類(被@Component註解或被其組合註解註解的類,比如@Service和@Repository)只有一個構造函數,並且參數和容器中的Bean可以對應,該Bean就會注入到該參數中。
-
把@Autowired註解到方法上:
import com.michael.annotation.demo.POJO.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
private Student student;
public void showInfo(){
System.out.println(this.student);
}
@Autowired
public void setStudent(Student student){
this.student = student;
}
}
-
重新啓動項目,觀察輸出;發現Student Bean被注入到了方法的參數上。如果該方法被@Bean註解,@Autowired可以被省略。
-
@Autowired可以註解參數,效果仍然一樣。