I am new to Guice. Is constructor injection preferred or field injection preferred?
Field injection appears to be quick and simple but testing would be a challenge as constructor is missing.
Thanks.
On their Minimize mutability wiki page, the Guice team says:
Minimize mutability
Wherever possible, use constructor injection to create immutable objects. Immutable objects are simple, shareable, and can be composed. Follow this pattern to define your injectable types:
[...]
Injecting methods and fields
Constructor injection has some limitations:
- Injected constructors may not be optional.
- It cannot be used unless objects are created by Guice. This is a dealbreaker for certain frameworks.
- Subclasses must call
super()
with all dependencies. This makes constructor injection cumbersome, especially as the injected base class changes.Method injection is most useful when you need to initialize an instance that is not constructed by Guice. Extensions like AssistedInject and Multibinder use method injection to initialize bound objects.
Field injection has the most compact syntax, so it shows up frequently on slides and in examples. It is neither encapsulated nor testable. Never inject final fields; the JVM doesn't guarantee that the injected value will be visible to all threads.