Search code examples
javaguice

Guice: Inject class with constructor with own parameters?


I have a problem with Guice. I would like to show this with an example. I want to pass the parameters of this constructor always dynamically, so e.g. new Test("bob", 765);. I also want some fields (like here SomeOtherObject) to be injected by Guice. How can I do this? Thanks in advance!

public class Test {

private String name;
private int id;

//Needs to be injected by Guice
@Inject
SomeOtherObject object;

public Test(String name, int id) {
    this.name = name;
    this.id = id;
}

}

Solution

  • Guice's AssistedInject feature is a good way to handle this.

    Basically you define a factory to get Test objects with:

    public interface TestFactory {
        public Test create(String name, int id);
    }
    

    Augment the Test class's @Inject constructor with @Assisted annotation:

    public class Test {
        @Inject
        public Test(SomeOtherObject object, @Assisted String name, @Assisted int id) {
            this.object = object;
            this.name = name;
            this.id = id;
        }
    }
    

    And then use FactoryModuleBuilder in your Module's configure:

    install(new FactoryModuleBuilder().build(TestFactory.class));
    

    And instead of constructing Tests directly, inject a TestFactory and use it to create Tests:

    public class OtherThing {
        @Inject
        TestFactory factory;
    
        public Test doStuff(Stirng name, int id) {
            return factory.create(name, id);
        }
    }
    

    Note: looking at the docs now, it appears that AutoFactory has been introduced as the preferred way to do this, and may be simpler.