Dagger 2 is the IOC framework under Android, similar to the Java server's spring, but functionally far from its power. Personal Understanding the essence of both app and server-dependent injection is the same, used to decouple the definition and implementation of a service. Let me give you the following simple example:
1. Add the following configuration in Android Studio:
Buildscript { repositories { jcenter () } dependencies { classpath ' com.android.tools.build: gradle:1.5.0 ', ' com.neenbedankt.gradle.plugins:android-apt:1.4+ ' //Note:do not place your application dependencies here; They belong //In the individual module Build.gradle files }}
Apply plugin: ' Android-apt '
///Note Here Dagger version number dependencies { compile filetree (dir: ' Libs ', include: [' *.jar ']) testcompile ' junit:junit:4.12 ' compile ' com.android.support:appcompat-v7:23.2.0 ' compile ' com.android.support:design : 23.2.0 ' compile ' com.google.dagger:dagger:2.0 ' apt ' com.google.dagger:dagger-compiler:2.0 ' provided ' Org.glassfish:javax.annotation:10.0-b28 '}
2, the implementation of the definition of services are as follows:
Public Interface istoreinfo { void storeinfo (String info);}
Public class Implements istoreinfo{ @Override publicvoid storeinfo (String info) { System.out.println ("in DB:" + info);} } Public class Implements istoreinfo{ @Override publicvoid storeinfo (String info) { System.out.println ("in File:" + info);} }
3. Define module and component
@Module Public class infoservicemodule { @Provides @Singleton istoreinfo setistoreinfo () { return New storeinfoinfile (); }}
= Infoservicemodule. class )publicinterface infoservicecomponent { void Inject (infoservice service); Istoreinfo setistoreinfo ();}
Note: This is actually equivalent to the part of the spring XML definition, but here is the definition and implementation of a hard-coded form binding interface
4. Use:
Public class Infoservice { @Inject public istoreinfo info; Public void Initservice () { = Daggerinfoservicecomponent.builder (). Infoservicemodule (new Infoservicemodule ()). build (); Component.inject (this); } Public void Infohandler (String input) { info.storeinfo (input);} }
Dagger 2 Basics