用Guice注入特定实例

时间:2013-05-25 09:19:51

标签: java dependency-injection guice

我在使用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对该字段进行了注释,但仍无效。

2 个答案:

答案 0 :(得分:3)

  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不是您的实现类。

  3. 这是文档:

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

    希望这有帮助。

答案 1 :(得分:1)

最好不要直接注入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);
    }
  }

}
相关问题