Answer the question
In order to leave comments, you need to log in
How to make @Inject into class fields work in Dagger 2?
Dependency injection in class fields does not work in Dagger 2.11.
Running code:
public class MainWindow {
@Inject ProfileJPanel profileJPanel;
@Inject
public MainWindow(){
System.out.println(profileJPanel.getName());
}
}
Exception in thread "main" java.lang.NullPointerException
at MainWindow.(MainWindow.java:8)
at MainWindow_Factory.get(MainWindow_Factory.java:20)
at MainWindow_Factory.get(MainWindow_Factory.java:6)
at DaggerMainComponent.createMainWindow(DaggerMainComponent. java:44)
at Main.main(Main.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Answer the question
In order to leave comments, you need to log in
Constructor injection and field injection are different. Constructor injection works like this - you list parameters and they are injected. That is like this:
public class MainWindow {
private final ProfileJPanel profileJPanel;
@Inject
public MainWindow(ProfileJPanel profileJPanel){
this.profileJPanel = profileJPanel;
System.out.println(profileJPanel.getName());
}
}
>> I do not advise you to mix.
Is it because dependency injection for a class happens in two steps - first in the constructor, then through the call to inject? Or are there any other considerations?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question