3

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

这是我目前拥有的:

class Driver {
   private ThreadLocal<Database> db;

   ...
}

我通常只是在构造函数中传递 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);
    }
 }

这是我实例化所有东西的方式:

Injector injector = new Injector(new MyGuiceModule(db));
Driver driver = injector.getInstance(Driver.class);

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

编辑:

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

4

2 回答 2

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

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

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

    bind(ThreadLocal.class).toInstance(this.dbToInject);
    

    通常,它会是这样的:

    bind(MyInterface.class).toInstance(MyImplementation.class);
    

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

这是文档:

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

希望这可以帮助。

于 2013-05-28T05:24:25.003 回答
2

最好不要ThreadLocal直接注入,而是将数据库注入构造函数(如@Tobias 建议的那样)。你真的想为创建的所有驱动程序实例使用相同的数据库吗(注意注释中的可选单例)?

public class GuiceExample {

  public static class MyGuiceModule extends AbstractModule {
    @Override
    protected void configure() {
      bind(Driver.class);
    }

    @Provides
    //Uncomment this to use the same Database for each Driver
    //@Singleton
    Database getDatabase() {
      return new Database();
    }
  }

  @Test
  public void testInjection() {
    Injector i = Guice.createInjector(new MyGuiceModule());
    i.getInstance(Driver.class);
  }

  public static class Database {}

  public static class Driver {
    ThreadLocal<Database> db = new ThreadLocal<Database>();

    @Inject
    Driver(Database db) {
      this.db.set(db);
    }
  }

}
于 2013-05-27T20:28:07.827 回答