简体   繁体   中英

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() {
  ...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM