简体   繁体   中英

Guice: the @Inject at static fields

Now I am reading the official documentation of PlayFramework, but it doesn't actually matter.

And I saw this sentence:

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

They explained it is deprecated to use @Inject annotation toward static fields. Why? I don't understand "break encapsulation". What do you think they mean by the sentence?

Maybe because stylistically

class Foo
{
  @Inject
  static String propery;
}

is equiavalent of

class Foo
{
  static String propery;

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

those who do not know implementation details can be surprised by result

It's kinda obvious OOP principle (encapsulation), so @Inject will provide an instance field (this is taken from Play documentation), then of course it will be strange to make it static, since ALL instances will share same object for field A, which is one of the possible problems and one of the definition of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM