com.google.inject.assistedinject
Class FactoryProvider<F,R>

java.lang.Object
  extended by com.google.inject.assistedinject.FactoryProvider<F,R>
Type Parameters:
F - The factory interface
R - The concrete class to be created.
All Implemented Interfaces:
Provider<F>

public class FactoryProvider<F,R>
extends Object
implements 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 RealPayment(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 concrete 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(PaymentFactory.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()
          Provides an instance of T.
static
<X,Y> FactoryProvider<X,Y>
newFactory(Class<X> factoryType, 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(Class<X> factoryType,
                                                    Class<Y> implementationType)

get

public F get()
Description copied from interface: Provider
Provides an instance of T. Must never return null.

Specified by:
get in interface Provider<F>