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?
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.
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