使用 Guice 注入特定实例

hal*_*arp 3 java dependency-injection guice

我在使用 Guice 注入特定字段实例时遇到了一些问题。

这是我目前拥有的:

class Driver {
   private ThreadLocal<Database> db;

   ...
}
Run Code Online (Sandbox Code Playgroud)

我通常只是在构造函数中传递 db 实例。但是这个类会被拦截,使用guice。

这是模块:

 class MyGuiceModule extends AbstractModule {

    private ThreadLocal<Database> dbToInject;

    public MyGuiceModule(ThreadLocal<Database> dbToInject) {
         this.dbToInject = dbToInject;
    }

    @Override
    protected void configure() {

         // Binds the interceptor.
         bindInterceptor(....);

         bind(ThreadLocal.class).toInstance(this.dbToInject);
    }
 }
Run Code Online (Sandbox Code Playgroud)

这是我实例化所有内容的方式:

Injector injector = new Injector(new MyGuiceModule(db));
Driver driver = injector.getInstance(Driver.class);
Run Code Online (Sandbox Code Playgroud)

我敢打赌这很明显,但我在这里做错了什么?

编辑:

对不起,如果我不清楚。我的问题是这不起作用。未注入实例。我已经用@Inject 注释了该字段,但仍然不起作用。

Min*_*gyu 5

  1. 我认为你需要使用Guice.createInjector来创建一个注入器实例。

    下面是我将如何创建一个注入器:

    Injector injector = Guice.createInjector(new MyGuiceModule(db));
    
    Run Code Online (Sandbox Code Playgroud)
  2. 另一件事是您使用以下代码执行绑定:

    bind(ThreadLocal.class).toInstance(this.dbToInject);
    
    Run Code Online (Sandbox Code Playgroud)

    通常,它会是这样的:

    bind(MyInterface.class).toInstance(MyImplementation.class);
    
    Run Code Online (Sandbox Code Playgroud)

    您的 ThreadLocal.class 不是接口类,而 this.dbToInject 也不是您的实现类。

这是文档:

http://code.google.com/p/google-guice/wiki/Motivation

希望这可以帮助。