I'm having a few problems injecting a specific field instance with Guice.
Here's what I currently have:
class Driver {
private ThreadLocal<Database> db;
...
}
I'd usually just pass the db instance in a constructor. But this class will be intercepted, using guice.
Here's the module:
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);
}
}
And here's how I'm instantiating all the stuff:
Injector injector = new Injector(new MyGuiceModule(db));
Driver driver = injector.getInstance(Driver.class);
I bet it's pretty obvious, but what am I doing wrong here?
EDIT:
Sorry if I wasn't clear. My problem is that this is not working. The instance is not being injected. I've annotated the field with @Inject and still doesn't work.
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));
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.
Here's the documentation:
http://code.google.com/p/google-guice/wiki/Motivation
Hope this helps.
It would probably be better not to inject the ThreadLocal
directly but to inject the Database into the constructor (as @Tobias suggested). And do you really want to use the same Database for all the instance of the Driver that are created (note the optional singleton in the comment)?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With