使用Guice注入特定实例

4

我在使用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注释了该字段,但仍然不起作用。


为什么不用 @Inject 注释来注释 Driver 构造函数? - Tobias Brandt
2
你遇到了什么确切的问题? - condit
你是否遇到了错误?你想要改进代码吗?这并不清楚。 - Jan Galinski
2个回答

6
  1. I think you need to use Guice.createInjector to create an injector instance.

    Here's how I would create an injector:

    Injector injector = Guice.createInjector(new MyGuiceModule(db));
    
  2. Another thing is you used the following code to perform binding:

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

    Usually, it would be something like:

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

    Your ThreadLocal.class is not an interface class, and this.dbToInject is not your implementation class.

这是文档: http://code.google.com/p/google-guice/wiki/Motivation 希望能帮到你。

我认为你所指的是Linked Bindings,但在上面的例子中,它是Instance Binding - bana

3

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

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);
    }
  }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接