Play Framework 2.4 - Injection fields are always zero

I have a simple injection module:

public class InjectionModule extends AbstractModule { @Override protected void configure() { bind(SomeModel.class); bind(SomeData.class); } } 

it is included in my application.conf application

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

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

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

handleRequest() simply making a promise and calling process() in the model.

In my SomeModel class SomeModel I am trying to introduce some dependencies, but they are always zero, which I do:

 @Inject private SomeData data; void process() { // do something // but data is always null } 

but data always null.

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

Update

I modified it to use constructor injection and it all works great, why doesn't my field injection work?

+5
source share
1 answer

First of all, the injector creates some kind of object and only after that inserts the values ​​into the object. Therefore, the entered properties will always be null in the constructor.

You go the right way to use constructor installation if you want values ​​to be entered in the constructor.

The best way is not to use a constructor, use property nesting and use some kind of method like "build" (this method cannot be called from the constructor). You can access the injected variables in any way other than the constructor.

+4
source

All Articles