Search code examples
javadependency-injectionguice

Using Guice method injection not as setter


Is it a bad practice to use method injection, and not as a setter?

Say I just need one variable to perform a task

@Inject
public void doThing(@Named(booleanA) boolean A) {
if (A) {
   ..
} else {
  ...
}

Should I go through the trouble of retaining an instance variable?

boolean A;
@Inject
public void setA(@NAmed(booleanA) boolean A) {
  this.A = A;
}

public void doThing() {
  ...
}

Solution

  • Yes, you should: Guice can't know when you want that task to be done, and it isn't intended to do work on its own, only to set up things to do work.