user3706481
user3706481

Reputation: 61

Guice Constructor injection or Field injection?

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.

Upvotes: 4

Views: 5798

Answers (3)

Sumukha H S
Sumukha H S

Reputation: 141

Both the types are fine. But you need to know when and where you need to use constructor injection.

Advantages of Constructor injection are,

  1. It Provides Immutability (If used Properly)
In Constructor Injection you can use something like this.

public class MemberResource {

     private final IMemberService memberService;

     @Inject
     public MemberResource(IMemberService memberService) {
         this.memberService = memberService;
     }

}

  1. Unit testing becomes easier.

Advantage of Field injection is less coding.

Upvotes: 0

Olivier Grégoire
Olivier Grégoire

Reputation: 35417

Use constructor injection

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.

Upvotes: 6

Karan Ashar
Karan Ashar

Reputation: 1400

Would like to point out some differences so you can decide for yourself:

  • With constructor injection you can use the final modifier. Can't do that with field injection. Advantages of final members are off-topic and you can read up on that.
  • Writing test cases with constructor injection is easy (like you already mentioned)
  • With constructor injection all dependencies are mandatory. In order to declare a class you would need to know all its required dependencies.
  • With field injection, you will hide your dependencies for the class instead of making them explicit.

Above are just a few points to think about. I personally prefer Constructor Injection because of ease of testing and final support.

Upvotes: 3

Related Questions