inject object without access to injector in Guice

I am working on an existing Java code base that uses Guice for Dependency Injection. I have a new class Foo that has one member field (bar) I wanted to inject in. Like this:

public class Foo {
    @Inject
    private Bar bar;
}

However, there are two things:

  1. There is no direct access to the injector where the Foo is used.
  2. The client wants to use "new" to create Foo.

Is it still possible to inject Bar into Foo object when the clients do:

myFoo = new Foo();

I am very new to DI and Guice, don't really understand how you can inject objects without calling injector.createInstance() on its class or its container class. It seems not working in my testing.

Answers


No DI tool works if you create your instances via "new" yourself. That's not guice specific. So unless you drop your constraint "2", you will have a hard time.


With Guice you can force the injection of fields if you have a reference to the injector. Like this:

injector.injectMembers(fooObject);

Your first point says you don't have access to the injector where Foo is used. Well, you can try to solve that giving Foo a static reference to the injector.

public class Foo {
  @Inject private static Injector injector;

  @Inject
  private Bar bar;

  public Foo() {
    injector.injectMembers(this);
  }
}

But wait, that won't work out of the box because the injector field would just be null. You need to inject it also but, as it is a static field, you just do it once. It is called static injection. Probably at application start where you have access to the Guice injector, in any of the guice modules.

There, you just execute this:

requestStaticInjection(Foo.class)

Need Your Help

Unit Testing Django Rest Framework Authentication at Runtime

django unit-testing django-rest-framework django-settings http-token-authentication

I basically want to turn TokenAuthentication on but only for 2 unit tests. The only option I've seen so far is to use @override_settings(...) to replace the REST_FRAMEWORK settings value.

UpdateModel with Dictionary/Hashtable

asp.net-mvc-2 dictionary hashtable

I'm trying out some MVC stuff and I was wondering if there's some way to edit dynamic fields.