如何在不执行模块“ new”的情况下将InstanceBinding绑定到类的两个不同实例?

时间:2018-07-25 15:46:58

标签: java guice

我有一个类Couple,它的构造函数中有两个Person。每个人都有不同的名字。我该如何进行设置,以便Guice可以很好地注入所有内容。 (Couple和Person是任意的。我认为它会比A和B更好)

public class Couple {
    private final Person person1;
    private final Person person2;

    public Couple(@Person1 Person person1, @Person2 Person person2) {
        this.person1 = person1;
        this.person2 = person2;
    }
}

public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }
}

public class CoupleModule {
    private final String name1;
    private final String name2;

    public CoupleModule(String name1, String name2) {
        this.name1 = name1;
        this.name2 = name2;
    }

    protected void configure() {
        install(new PersonModule(name1, name2));
        bind(Couple.class);
    }
}

现在,我只是绑定到一个实例并为Persons调用new。

public class PersonModule {
    private final String name1;
    private final String name2;

    public PersonModule(String name1, String name2) {
        this.name1 = name1;
        this.name2 = name2;
    }

    protected void configure() {
        bind(Person.class)
             .annotatedWith(Person1.class)
             .toInstance(new Person(name1));

        bind(Person.class)
             .annotatedWith(Person2.class)
             .toInstance(new Person(name2));
    }
}

但我宁可不要叫新的。一种选择是使用两种提供方法:

@Provides @Person1
Person providePerson1() {
    return new Person(name1);
}

@Provides @Person2
Person providePerson2() {
    return new Person(name2);
}

但是,我仍然在模块中调用new。我更喜欢让吉斯(Guice)完成这项工作。如果只有一个人,我会将名称绑定到带注释的String。

protected void configure() {
    bind(String.class)
        .annotatedWith(Name.class)
        .toInstance(name);
    bind(Person.class);
}

现在,我想使用相同的方式,但是根据我要绑定的人绑定到另一个String。我想做类似的事情:

protected void configure() {
    bind(Person.class)
        .annotatedWith(Person1.class)
        .withBinding(String.class)
        .annotatedWith(Name.class)
        .toInstance(name1)

    bind(Person.class)
        .annotatedWith(Person2.class)
        .withBinding(String.class)
        .annotatedWith(Name.class)
        .toInstance(name2)
}

Guice有可能吗?

0 个答案:

没有答案
相关问题