Inject into private, package or public field or pr

2019-02-08 09:56发布

I see many Java examples using dependency injection with private fields without a public setter like this:

public SomeClass {
  @Inject
  private SomeResource resource;
}

But that is a bad idea when the injection should be performed manually for example in unit tests.

There are several possibilities to solve this:

  • add a public setter: setSomeResource(SomeResource r)
  • make the field public
  • make the field package protected

I'd like to avoid the setter, since nothing really happens in it. So I'd prefer public or package protected. What do you recommend?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-08 10:56

With field based injection, you run into the issue you describe with testing. Also with setter based injection, an instance of a class can be created in an incomplete state when running tests if you forget to set some of the dependencies. I have been practicing constructor injection most recently due to the fact that it forces you to set all dependencies whenever you create an instance of a class during testing. The answer above by Andre Rodrigues explains how this would be accomplished.

查看更多
登录 后发表回答