Guice Provider注入

时间:2018-10-16 14:52:27

标签: java dependency-injection guice

我正在使用Guice for DI,我想将同一接口的多个实例注入到调用类中。类的层次结构如下:

public interface MyInterface<T, U> {
    public T getX(U u);
}

public abstract class MyAbstractClass<T, U> implements MyInterface<T, U> {
    public void routineStuff() {
        ...
    }
}

public class MyImplOne extends MyAbstractClass<T1, U1> {
    public T1 getX(U1 u) {
        return new T1(u);
    }
}

public class MyImplTwo extends MyAbstractClass<T2, U2> {
    public T2 getX(U2 u) {
        return new T2(u);
    }
}

public class MainClass {
    @Inject
    public MainClass(Provider<MyInterface> myInterface) {
    }

    public void DoX1() {
         myInterface.get().getX().print();  // should inject MyImplOne
    }

    public void DoX2() {
         myInterface.get().getX().print();  // should inject MyImplTwo
    }
}

Guice有可能吗?我是否需要编写Provider类,以便为MyImplOne和MyImplTwo提供必需的对象,在这种情况下,配置应该是什么样的?

0 个答案:

没有答案