assistedinject
Class FactoryProvider<F,R>

java.lang.Object
  extended by assistedinject.FactoryProvider<F,R>
All Implemented Interfaces:
com.google.inject.Provider<F>

public class FactoryProvider<F,R>
extends java.lang.Object
implements com.google.inject.Provider<F>

Provides a mechanism to combine user-specified paramters with Injector-specified paramters when creating new objects.

To use a FactoryProvider:

Annotate your implementation class' constructor with the @AssistedInject and the user-specified parameters with @Assisted:

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

Write an interface with a create method that accepts the user-specified parameters in the same order as they appear in the implementation class' constructor:

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

You can name your create methods whatever you like, such as create, or createPayment or newPayment. The implementation class must be assignable to the return type of your create method. You can also provide multiple factory methods, but there must be exactly one @AssistedInject constructor on the implementation class for each.

In your Guice module, bind your factory interface to an instance of FactoryProvider that was created with the same factory interface and implementation type:

  bind(FooFactory.class)
     .toProvider(FactoryProvider.newFactory(PaymentFactory.class, RealPayment.class));

Now you can @Inject your factory interface into your Guice-injected classes. When you invoke the create method on that factory, the FactoryProvider will instantiate the implementation class using parameters from the injector and the factory method.

public class PaymentAction {
    @Inject private PaymentFactory paymentFactory;

    public void doPayment(Money amount) {
       Payment payment = paymentFactory.create(new Date(), amount);
       payment.apply();
    }
 }


Method Summary
 F get()
           
static
<X,Y> FactoryProvider<X,Y>
newFactory(java.lang.Class<X> factoryType, java.lang.Class<Y> implementationType)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

newFactory

public static <X,Y> FactoryProvider<X,Y> newFactory(java.lang.Class<X> factoryType,
                                                    java.lang.Class<Y> implementationType)

get

public F get()
Specified by:
get in interface com.google.inject.Provider<F>