Search code examples
javabindguice

Guice how to bind one class with different paramaters?


I want to create two instances with one class by injecting different parameter. For example:

class Foo {
  private String config;
}

I want two Foo instances, one's config is A, another one is B, how should I do?


Solution

  • There are lots of different ways to achieve what you are after. without a little more information of your use case its hard to say the better of the ways.

    For this answer i'll limit the scope to provide you with an example of a provider type solution.

    first fully defined your class

        private class Foo {
        private String config;
    
        public Foo(final String config)
        {
            this.config = config;
        }
    }
    

    In your GuiceModule.java create 2 different providers

    @Provides
    @Named("foo1")
    public Foo provideFoo1() {
        return new Foo("value1");
    }
    
    @Provides
    @Named("foo2")
    public Foo provideFoo2() {
        return new Foo("value2");
    }
    

    and then these objects can be injected into a single object (like below) or multiple different objects

    private class ManagerManager {
    @Inject
    public ManagerManager(
            @Named("foo1") final Foo config,
            @Named("foo2") final Foo config2) {}
    }
    

    if injecting one of them into multiple objects, you may wish to have a singleton concept for both Foo1 and Foo2, so add @Singleton onto the provider

    if you have a use case that the value (for foo1/foo2) is not known until runtime, then its better to ask for an example of an assistedFactory