I have the below code to do dependency injection using Guice. The first one is using constructor injection while the other one is adding @Inject
directly above the field. Is there any difference between these two ways? It seems that constructor injection is recommended on the Guice official website.
class BillingService {
private final CreditCardProcessor processor;
private final TransactionLog transactionLog;
@Inject
BillingService(CreditCardProcessor processor, TransactionLog transactionLog) {
this.processor = processor;
this.transactionLog = transactionLog;
}
...
}
And:
class BillingService {
@Inject
private final CreditCardProcessor processor;
@Inject
private final TransactionLog transactionLog;
BillingService() {
}
...
}
The differences I would point:
final
modifier, i.e. your code above won't compile. Commenting the advantages of final members is off-topic here.