[英]annotation in spring boot @autowired
我一直在編碼基本的 java 一段時間,現在正在體驗 spring 引導。
在 spring 引導中經常看到注釋。
對我來說,注釋是為了節省開發人員的時間來實現更少的代碼,在線定義。 但這不能滿足我下面的問題
到目前為止,我正在體驗@autowired。 讓我感到困惑的是@autowired 啟用依賴注入並告訴 bean 配置 xml (我還不明白它有多大用處)
例如,
class A {
private int id;
// With setter and getter method
}
class B {
private String name;
@Autowired
A a;
B(A a){this.a = a} ;
}
}
但是,不是說,在基本的 java 中,它一直允許在沒有 @autowired 的情況下將實例作為參數傳遞嗎? 為什么這突然變成了一個好處? 或者我錯過了什么?
class A {
private int id;
// With setter and getter method
}
class B {
private String name;
A a;
B(A a){this.a = a} ;
}
}
當你這樣做時你會得到好處(雖然不推薦)
@Component
class A {
private int id;
// With setter and getter method
}
@Component
class B {
private String name;
@Autowired
A a;
B() {
}
}
現在,假設這些類位於 @SpringBootApplication 注釋 class 的相同或子包中,將為您自動配置,並且 A 將通過 Spring 框架使用反射注入到 B 中。
但是,正如我提到的,不建議這樣做,您可能希望通過構造函數注入它,因為這會使您的組件更容易測試(您可以輕松地注入一個模擬)。 請注意,當您的組件/bean 的構造函數采用 arguments @Autowired 時,spring 將嘗試為您找到要注入其中的 bean。
@Component
class A {
private int id;
// With setter and getter method
}
@Component
class B {
private String name;
final A a;
B(A a) {
this.a = a;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.