Juan
Juan

Reputation: 126

Guice field injection

So here's the thing. I'm trying to inject some fields with guice, but it turns out that they are always null (not trying to use them on the constructor).

public class A {

    @Inject
    private SomeClass bar;

    public A() {
        foo();
    }

    public someMethod() {
        bar.doSth();
    }

}

public class B {

    private A a;

    public B() {
        a = new A();
    }

    public someOtherMethod() {
        a.someMethod();
    }

}

Now whenever the app executed someOtherMethod and a tries to run bar.doSth a nice NullPointerException is raised.

So in order to fix this i ended Injecting the field manually inside the constructor:

public A() {
    final Injector injector = Guice.createInjector();
    bar = injector.getInstance(SomeClass.class);
}

But this is ugly, unclear, has a lot of boilerplate and I'm forced to do it on many places which make it tedious.

Is there any other way to archive this? Or an explanation of why the field is not being injected?

Thanks

Note: I'm currently unavailable to do the propper injection on the constructor (with bar as a parameter) because of the refactoring it would imply. The project is now under heavy production and thus this kind of refactoring can't be done right now.

Upvotes: 1

Views: 1731

Answers (1)

Floegipoky
Floegipoky

Reputation: 3273

The IOC container only controls what you tell it to control. It doesn't know about the A inside of B, because it's being constructed directly, not managed by the container. You need to inject the A as well:

public class B {
    @inject private A a;

    public B() {}

    ...
}

And you can't just call new B() either, you need to inject the B as well.

Upvotes: 2

Related Questions