在我发现的所有Guice示例中,获取实例都涉及使用具体类作为参数调用Injector.getInstance()
。有没有办法仅使用接口从Guice获取实例?
public interface Interface {}
public class Concrete implements Interface {}
Interface instance = injector.getInstance(Interface.class);
谢谢
最佳答案
实际上,这正是Guice的目的。
为了使getInstance()与接口一起使用,您需要首先在模块中绑定该接口的实现。
因此,您将需要一个类似于以下内容的类:
public class MyGuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(Interface.class).to(Concrete.class);
}
}
然后,在创建注射器时,您只需要在以下位置传递模块的实例:
Injector injector = Guice.createInjector(new MyGuiceModule());
现在,您对
injector.getInstance(Interface.class)
的调用应该使用默认构造函数返回Concrete的新实例。当然,还有许多其他方法可以进行绑定,但这可能是最直接的方法。