在我发现的所有Guice示例中,获取实例涉及Injector.getInstance()使用具体类作为参数进行调用.有没有办法只使用接口从Guice获取实例?
public interface Interface {}
public class Concrete implements Interface {}
Interface instance = injector.getInstance(Interface.class);
Run Code Online (Sandbox Code Playgroud)
谢谢
实际上,这正是Guice的目标.
为了使getInstance()与接口一起工作,您需要首先在模块中绑定该接口的实现.
所以你需要一个看起来像这样的类:
public class MyGuiceModule extends AbstractModule {
@Override
protected void configure() {
bind(Interface.class).to(Concrete.class);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当您创建注射器时,您只需要传递模块的实例:
Injector injector = Guice.createInjector(new MyGuiceModule());
Run Code Online (Sandbox Code Playgroud)
现在,您的调用injector.getInstance(Interface.class)应该使用默认构造函数返回Concrete的新实例.
当然,还有很多方法可以进行绑定,但这可能是最直接的.
| 归档时间: |
|
| 查看次数: |
3228 次 |
| 最近记录: |