參考:https://blog.csdn.net/weixin_50055999/article/details/147493914?utm_source=miniapp_weixin
Setter 方法注入 (Setter Injection)
在類中提供一個 setter 方法,并在該方法上使用 @Autowired、@Resource 等注解。
代碼示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class OrderService {private PaymentService paymentService;// 使用 @Autowired 進行 Setter 注入@Autowiredpublic void setPaymentService(PaymentService paymentService) {this.paymentService = paymentService;}// 也可以使用 @Resource// @Resource// public void setInventoryService(InventoryService inventoryService) {// this.inventoryService = inventoryService;// }public void processOrder(Order order) {boolean paid = paymentService.pay(order.getAmount());if (paid) {System.out.println("Order processed successfully.");}}
}
優點:
支持循環依賴:Spring 的 setter 注入可以解決某些類型的循環依賴問題(A 依賴 B,B 依賴 A)。
依賴可變:允許在對象創建后重新設置依賴(雖然這在實踐中不常見且可能帶來問題)。
比字段注入更“顯式”:依賴通過方法暴露出來。
便于單元測試:可以在測試中直接調用 setPaymentService(mockPaymentService) 來注入模擬對象。
缺點:
代碼稍多:需要編寫額外的 setter 方法。
對象可能處于不完整狀態:對象可以被創建,但依賴可能還沒有通過 setter 注入,如果在注入前就使用,會導致 NPE。雖然 Spring 保證在初始化完成后才暴露 Bean,但設計上不如構造函數注入“強制”。
可以被意外覆蓋:setter 方法是公開的,理論上可以在運行時被多次調用,改變依賴。