Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework 2.4 - Injected fields are always null

I have a simple injection module:

public class InjectionModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(SomeModel.class);
        bind(SomeData.class);
    }
}

it is enabled in my application.conf

play {
  modules {
    enabled += "com.example.InjectionModule"
  }
}

In my controller I want to create a new model, and I do so like this:

public Promise<Result> getPage() {
    return handleRequest(() -> Play.application().injector().instanceOf(SomeModel.class));
}

handleRequest() just deals with creating the promise and calling process() on the model.

In my SomeModel class I attempt to inject some dependencies but they are always null, what I am doing is:

@Inject
private SomeData data;

void process() {
    // do something
    // but data is always null
}

but data is always null.

Note that if I just use new SomeData() then it works.

Update

I changed it to use constructor injection and it all works fine, why did my field injection not work?

like image 256
Neilos Avatar asked Sep 26 '22 18:09

Neilos


1 Answers

First of all injector creates some object and only after this inject values in to the object. So injected properties would be always null in the constructor.

You are going by right way to use constructor injection if you want to have injected values in the constructor.

The best way would be do not use constructor, use injection on the properties, and use some method like "build" (this method must not be called from the constructor). You could access injected variables in any method but constructor.

like image 106
Andriy Kuba Avatar answered Sep 29 '22 07:09

Andriy Kuba