在方法或构造函数中注入依赖项?

Jim*_*Jim 20 dependency-injection

依赖注入似乎是一件好事.一般来说,应该在需要它们的方法中注入依赖项,还是应该在类的构造函数中注入依赖项?

请参阅下面的示例以演示注入相同依赖项的两种方法.

//Inject the dependency into the methods that require ImportantClass
Class Something {

    public Something()
    {
         //empty
    }

    public void A() 
    {
         //do something without x
    }

    public void B(ImportantClass x)
    {
         //do something with x
    }

    public void C(ImportantClass x)
    {
         //do something with x
    }
}

//Inject the dependency into the constructor once
Class Something {
    private ImportantClass _x
    public Something(ImportantClass x)
    {
         this._x = x;
    }

    public void A() 
    {
         //do something without x
    }

    public void B()
    {
         //do something with this._x
    }

    public void C()
    {
         //do something with this._x
    }

}
Run Code Online (Sandbox Code Playgroud)

joh*_*tok 14

构造函数注入的主要好处是它允许您的字段标记为final.例如:

class Foo {
    private final Bar _bar;

    Foo(Bar bar) {
        _bar=bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下页面列出了专业人士和骗子:Guice Best Practices:

方法注入

  • +不是现场注入
  • +只适用于某些奇怪边缘情况的东西

构造函数注入

  • +菲尔兹可以是最终的!
  • +注入不可能被跳过
  • +一目了然易于查看依赖项
  • +这就是建筑的概念
  • - 无可选注射
  • - 当DI库本身无法进行实例化时无用
  • - 子类需要"了解"他们的超类所需的注射
  • - 对于仅"关心"其中一个参数的测试不太方便