天天看點

Spring 有哪幾種依賴注入方式?官方是怎麼建議使用的呢?

IDEA 提示 Field injection is not recommended

在使用IDEA 進行Spring 開發的時候,當你在字段上面使用@Autowired注解的時候,你會發現IDEA 會有警告提示:

Field injection is not recommended

Inspection info: Spring Team Recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".

Spring 有哪幾種依賴注入方式?官方是怎麼建議使用的呢?

翻譯過來就是這個意思:

不建議使用基于 field 的注入方式。

Spring 開發團隊建議:在你的Spring Bean 永遠使用基于constructor 的方式進行依賴注入。對于必須的依賴,永遠使用斷言來确認。

比如如下代碼:

@Service
public class HelpService {
    @Autowired
    @Qualifier("svcB")
    private Svc svc;

    public void sayHello() {
        svc.sayHello();
    }
}

public interface Svc {
    void sayHello();
}

@Service
public class SvcB implements Svc {
    @Override
    public void sayHello() {
        System.out.println("hello, this is service B");
    }
}      

将光标放到

@Autowired

處,使用

Alt + Enter

快捷進行修改之後,代碼就會變成基于Constructor的注入方式,修改之後:

@Service
public class HelpService {
    private final Svc svc;

    @Autowired
    public HelpService(@Qualifier("svcB") Svc svc) {
        // Assert.notNull(svc, "svc must not be null");
        this.svc = svc;
    }

    public void sayHello() {
        svc.sayHello();
    }
}      

如果按照Spring 團隊的建議,如果svc是必須的依賴,應該使用Assert.notNull(svc, "svc must not be null")來确認。

修正這個警告提示固然簡單,但是我覺得更重要是去了解為什麼Spring 團隊會提出這樣的建議?直接使用這種基于 field 的注入方式有什麼問題?

首先我們需要知道,Spring 中有這麼3種依賴注入的方式:

基于 field 注入(屬性注入)

基于 setter 注入

基于 constructor 注入(構造器注入)

1. 基于 field 注入

所謂基于 field 注入,就是在bean的變量上使用注解進行依賴注入。本質上是通過反射的方式直接注入到field。這是我平常開發中看的最多也是最熟悉的一種方式,同時,也正是 Spring 團隊所不推薦的方式。比如:

@Autowired
private Svc svc;      

2. 基于 setter 方法注入

通過對應變量的

setXXX()

方法以及在方法上面使用注解,來完成依賴注入。比如:

private Helper helper;

@Autowired
public void setHelper(Helper helper) {
    this.helper = helper;
}      

注:在 Spring 4.3 及以後的版本中,setter 上面的 @Autowired 注解是可以不寫的。

推薦一個 Spring Boot 基礎教程及實戰示例:

https://github.com/javastacks/javastack

3. 基于 constructor 注入

将各個必需的依賴全部放在帶有注解構造方法的參數中,并在構造方法中完成對應變量的初始化,這種方式,就是基于構造方法的注入。比如:

private final Svc svc;

@Autowired
public HelpService(@Qualifier("svcB") Svc svc) {
    this.svc = svc;
}      

在 Spring 4.3 及以後的版本中,如果這個類隻有一個構造方法,那麼這個構造方法上面也可以不寫 @Autowired 注解。

基于 field 注入的好處

正如你所見,這種方式非常的簡潔,代碼看起來很簡單,通俗易懂。你的類可以專注于業務而不被依賴注入所污染。你隻需要把@Autowired扔到變量之上就好了,不需要特殊的構造器或者set方法,依賴注入容器會提供你所需的依賴。

基于 field 注入的壞處

成也蕭何敗也蕭何

基于 field 注入雖然簡單,但是卻會引發很多的問題。這些問題在我平常開發閱讀項目代碼的時候就經常遇見。

容易違背了單一職責原則

使用這種基于 field 注入的方式,添加依賴是很簡單的,就算你的類中有十幾個依賴你可能都覺得沒有什麼問題,普通的開發者很可能會無意識地給一個類添加很多的依賴。

但是當使用構造器方式注入,到了某個特定的點,構造器中的參數變得太多以至于很明顯地發現something is wrong。擁有太多的依賴通常意味着你的類要承擔更多的責任,明顯違背了單一職責原則(SRP:Single responsibility principle)。

這個問題在我司的項目代碼真的很常見。

依賴注入與容器本身耦合

依賴注入架構的核心思想之一就是受容器管理的類不應該去依賴容器所使用的依賴。換句話說,這個類應該是一個簡單的POJO(Plain Ordinary Java Object)能夠被單獨執行個體化并且你也能為它提供它所需的依賴。

這個問題具體可以表現在:

你的類和依賴容器強耦合,不能在容器外使用

你的類不能繞過反射(例如單元測試的時候)進行執行個體化,必須通過依賴容器才能執行個體化,這更像是內建測試

不能使用屬性注入的方式建構不可變對象(final 修飾的變量)

Spring 開發團隊的建議

Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies.

簡單來說,就是

強制依賴就用構造器方式

可選、可變的依賴就用setter 注入

當然你可以在同一個類中使用這兩種方法。構造器注入更适合強制性的注入旨在不變性,Setter注入更适合可變性的注入。

讓我們看看Spring 這樣推薦的理由,首先是基于構造方法注入,

The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. Furthermore constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.

Spring 團隊提倡使用基于構造方法的注入,因為這樣一方面可以将依賴注入到一個不可變的變量中 (注:final 修飾的變量),另一方面也可以保證這些變量的值不會是 null。此外,經過構造方法完成依賴注入的元件 (注:比如各個 service),在被調用時可以保證它們都完全準備好了。與此同時,從代碼品質的角度來看,一個巨大的構造方法通常代表着出現了代碼異味,這個類可能承擔了過多的責任。

而對于基于 setter 的注入,他們是這麼說的:

Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.

基于 setter 的注入,則隻應該被用于注入非必需的依賴,同時在類中應該對這個依賴提供一個合理的預設值。如果使用 setter 注入必需的依賴,那麼将會有過多的 null 檢查充斥在代碼中。使用 setter 注入的一個優點是,這個依賴可以很友善的被改變或者重新注入。

小結

以上就是本文的所有内容,希望閱讀本文之後能讓你對Spring 的依賴注入有更深的了解。