Java – dagger: field injection in POJO

I've never tried guide or other Di libraries, but I've tried to use the dagger from square for Android application It applies to frgements, but not POJO User guide assumes some knowledge about Di because it is not explained in more detail What can I do to inject restadapater into my POJO If I use the same code for field injection, it can be used in fragment

public class MyApplication extends Application {
    private ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        objectGraph = ObjectGraph.create(new DIModule(this));

    }

    public ObjectGraph objectGraph() {
        return objectGraph;
    }

    public void inject(Object object) {
        objectGraph.inject(object);
    }

    ...
    @Module(entryPoints = { 
    MainActivity.class,.....,Auth.class,RestAdapter.class
    })
    static class DIModule {@Provides
        @Singleton
        public RestAdapter provideRestAdapter() {
            return new RestAdapter.Builder().setServer(
                    new Server(Const.BASE_URL)).build();
        }
    }
}

// POJO

public class Auth {

    @Inject
    RestAdapter restAdapater;


    String Username;
    String Password;

    public String authenticate() {
     ...

     Api api = restAdapater.create(..)  // **restAdapater is null**

     }
}

All fragments come from below and di works normally In a recent talk by Eric Burke, he explained that this is necessary because Android constructs objects

public class BaseFragment extends Fragment {
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        ((MyApplication) getActivity()
                .getApplication())
                .inject(this);
    }

}

Solution

If you create an auth instance yourself, dagger will not know the instance and cannot inject dependencies for you

Because you have declared Auth in module entrypoints Class, so you only need to ask objectgraph for an auth instance:

Auth auth = objectGraph.get(Auth.class);

Then dagger knows what it needs to provide an auth instance and injects it into restadapter

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>