Pass parameter to constructor with Guice

后端 未结 4 1162
自闭症患者
自闭症患者 2020-12-04 07:53

I have a factory as below,

public final class Application {

    private static IFoo foo;

    public static IFoo getFoo(String bar)
    {
        // i need         


        
4条回答
  •  無奈伤痛
    2020-12-04 08:41

    I know that this is old thread but I just hit the issue myself today. I only need two or maximum three different instances of 'Foo' and I really didn't want to write all the bolierplate code of Factory. With a little googling I found this Stubbisms – Tony’s Weblog I would suggest this solution which is perfect if you know exactly what instances you need.

    In Guice module:

        bind(Foo.class).annotatedWith(Names.named("firstFoo")).toProvider(new Provider() {
            @Override
            public Foo get() {
                return new FooImpl("topic A");
            }
        });
        bind(Foo.class).annotatedWith(Names.named("secondFoo")).toProvider(new Provider() {
            @Override
            public Foo get() {
                return new FooImpl("topic B");
            }
        });
    

    Or in java 8:

        bind(Foo.class).annotatedWith(Names.named("firstFoo")).toProvider(() -> new FooImpl("first"));
        bind(Foo.class).annotatedWith(Names.named("secondFoo")).toProvider(() -> new FooImpl("second"));
    

    And in constructor of your service where you need Foo instances:

    @Inject
    public MyService (
        @Named("firstFoo") Foo firstFoo,
        @Named("secondFoo") Foo secondFoo) {
    }
    

    And Foo in my case:

    public class FooImpl implements Foo {
    
        private String name;
    
        public FooImpl(String name) {
            this.name = name;
        }
    
        @Override
        public String getName() {
            return name;
        }
    }
    

    Hope it helps someone.

提交回复
热议问题