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?
One way to avoid creating a setter for the field is using constructor injection. This even allows you to declare the field as final.
It goes like this: