Guice:静态字段的@Inject

Guice: the @Inject at static fields

现在正在看PlayFramework的官方文档,其实也无所谓

然后我看到了这句话:

Note that those are instance fields. It generally doesn’t make sense to inject a static field, since it would break encapsulation.

他们解释说不推荐对静态字段使用 @Inject 注释。为什么? 我不明白"break encapsulation"。你认为这句话是什么意思?

可能是因为风格上的原因

class Foo
{
  @Inject
  static String propery;
}

相当于

class Foo
{
  static String propery;

  Foo(String property) {
    this.property = property;
  }
}

不知道实现细节的人可能会对结果感到惊讶

有点明显的OOP原则(封装),所以@Inject会提供一个实例字段(这个取自Play文档),那么当然让它静态会很奇怪,因为ALL 个实例将共享字段 A 的相同对象,这是可能的问题之一,也是 breaking encapsulation

的定义之一

This API is not recommended for general use because it suffers many of the same problems as static factories: it's clumsy to test, it makes dependencies opaque, and it relies on global state.