【问题标题】:Injecting specific instance with Guice使用 Guice 注入特定实例
【发布时间】:2013-05-28 13:30:15
【问题描述】:

我在使用 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 构造函数?
  • 您遇到的具体问题是什么?
  • 您是否收到错误消息?你想改进代码吗?不清楚。

标签: java dependency-injection guice


【解决方案1】:
  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

希望这会有所帮助。

【讨论】:

【解决方案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);
    }
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    相关资源
    最近更新 更多