Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Guice's AssistedInject?

I've read https://github.com/google/guice/wiki/AssistedInject, but it doesn't say how to pass in the values of the AssistedInject arguments. What would the injector.getInstance() call look like?

like image 486
Noel Yap Avatar asked Jan 23 '12 17:01

Noel Yap


People also ask

When should I use AssistedInject?

AssistedInject allows you to dynamically configure Factory for class instead of coding it by yourself. This is often useful when you have an object that has a dependencies that should be injected and some parameters that must be specified during creation of object.

What is Guice AssistedInject?

AssistedInject in Guice 3.0 Guice 3.0 improves AssistedInject by offering the ability to allow different factory methods to return different types or different constructors from one type.

What is Assisted Inject?

Assisted injection is a dependency injection (DI) pattern that is used to construct an object where some parameters may be provided by the DI framework and others must be passed in at creation time (a.k.a “assisted”) by the user.

What is com Google inject?

Package com. google. inject Description. Google Guice (pronounced "juice") is an ultra-lightweight dependency injection framework.


1 Answers

Check the javadoc of FactoryModuleBuilder class.

AssistedInject allows you to dynamically configure Factory for class instead of coding it by yourself. This is often useful when you have an object that has a dependencies that should be injected and some parameters that must be specified during creation of object.

Example from the documentation is a RealPayment

public class RealPayment implements Payment {    @Inject    public RealPayment(       CreditService creditService,       AuthService authService,       @Assisted Date startDate,       @Assisted Money amount) {      ...    }  } 

See that CreditService and AuthService should be injected by container but startDate and amount should be specified by a developer during the instance creation.

So instead of injecting a Payment you are injecting a PaymentFactory with parameters that are marked as @Assisted in RealPayment

public interface PaymentFactory {     Payment create(Date startDate, Money amount); } 

And a factory should be binded

install(new FactoryModuleBuilder()      .implement(Payment.class, RealPayment.class)      .build(PaymentFactory.class)); 

Configured factory can be injected in your classes.

@Inject PaymentFactory paymentFactory; 

and used in your code

Payment payment = paymentFactory.create(today, price); 
like image 117
Mairbek Khadikov Avatar answered Nov 08 '22 07:11

Mairbek Khadikov