Pass parameter to constructor with Guice

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)