A
A
Alexander Kardapolov2017-06-26 16:39:49
Java
Alexander Kardapolov, 2017-06-26 16:39:49

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());
    }
}

Leads to NPE:
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)

The test case is available at the link:
https://github.com/akardapolov/sample_dagger2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2017-06-26
@akardapolov

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());
    }
}

And to inject fields, you need to call the inject method of your component for a specific object.
I don't recommend mixing.

A
Alexander Kardapolov, 2017-06-27
@akardapolov

>> 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 question

Ask a Question

731 491 924 answers to any question