Pass parameter to constructor with Guice

DarthVader picture DarthVader · Feb 11, 2012 · Viewed 47.4k times · Source

I have a factory as below,

public final class Application {

    private static IFoo foo;

    public static IFoo getFoo(String bar)
    {
        // i need to inject bar to the constructor of Foo
        // obvious i have to do something, not sure what
        Injector injector = Guice.createInjector();
        logger = injector.getInstance(Foo.class);
        return logger;              
    }

}

This is the Foo definition:

class Foo
{
   Foo(String bar)
   {

   }

}

OK. I m not sure how I can pass this parameter to Foo constructor with Guice?

Any ideas?

Answer

DougA picture DougA · Feb 11, 2012

All the "Guice Constructor Parameter" answers seem to be incomplete in some way. Here is a complete solution, including usage and a visual:

enter image description here

interface FooInterface {
    String getFooName();
}

// Annotate the constructor and assisted parameters on the implementation class

class Foo implements FooInterface {
    String bar;

    @Inject
    Foo(@Assisted String bar) {
        this.bar = bar;
    }

    // return the final name
    public String getFooName() {
        return this.bar;
    }

}

// Create a factory interface with a create() method that takes only the assisted parameters.

// FooFactory interface doesn't have an explicit implementation class (Guice Magic)

interface FooFactory {
    Foo create(String bar);
}

// Bind that factory to a provider created by AssistedInject

class BinderModule implements Module {

    public void configure(Binder binder) {
        binder.install(new FactoryModuleBuilder()
                .implement(FooInterface.class, Foo.class)
                .build(FooFactory.class));
    }
}

// Now use it:

class FooAction {
    @Inject private FooFactory fooFactory;

    public String doFoo() {
        // Send bar details through the Factory, not the "injector"
        Foo f = fooFactory.create("This foo is named bar. How lovely!");
        return f.getFooName(); // "This foo is named bar. How lovely!"
    }
}

Lots of helps here: https://google.github.io/guice/api-docs/latest/javadoc/index.html?com/google/inject/assistedinject/FactoryModuleBuilder.html