Android dependency injection: Dagger 2 example (1), androiddagger
This article is original, reproduced please indicate the source: http://blog.csdn.net/zjbpku
Dagger has been introduced in previous blog posts (Android dependency injection: Dagger instance introduction (Demo download). In this article, Dagger 2 is mainly based on Google technology.
People involved in the development, of course, everyone from Square and some other Contributors have contributed a lot. This project is probably started from January 1, last November.
The object is still in progress. The Snapshot version is just released soon. From the content provided by Github, it will soon be Pre Release Version, followed by the Release Version.
It is still in the Pre-Release version and is not stable yet. Please use it with caution. The Pre-Release version is relatively stable and can be used for project development. I am still paying attention to this project, and I will pass one in advance
Demo to briefly introduce Dagger 2.
Dagger 2 is an enhanced version of Dagger 1. x. In Dagger 1. x, @ Inject and @ Provides annotation constitute the graph of the object, relying on dependencies
Link. You can easily call code through the defined Graph Set (ObjectGraph. In Dagger 2, this relationship is replaced by an interface with a non-argument method,
The type returned by this method is the required type. The implementation of this interface is defined by @ Component annotation and passing in the modules parameter. For example:
@Component(// dependencies = ApplicationComponent.class, modules = ActivityModule.class)public interface ActivityComponent { MainActivity injectActivity(MainActivity activity); ToastHelper getToastHelper();}
During compilation, Dagger 2 will automatically generate the Dagger_AcitvityComponent implementation of this interface prefixed with Dagger _. Obtain
Instance. Use the builder returned by this method to set other Dependencies and build to obtain a new instance.
this.component = Dagger_ActivityComponent.builder()// .applicationComponent(((DaggerApplication) getApplication()).getComponent()) .activityModule(new ActivityModule(this)) .build();
In addition, if the method in the @ Component annotation interface does not have parameters, a create () method will be generated in the generated instance. This create () method is actually
Builder (). build (); this point will be mentioned in future code.
The following is a Demo:
The Demo uses the latest version of AndroidStudio (hereinafter referred to AS) 1.0.2. Since the AS version is used, the configuration of the gradle. build File is indispensable. The gradle configuration of this project is AS follows:
apply plugin: 'com.android.application'apply plugin: 'android-apt'buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.0.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' // 3 }}allprojects { repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } }}android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.example.zjbpku.dagger2" minSdkVersion 19 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}def Dagger2_Version = '2.0-SNAPSHOT'dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' // 1. Dagger 2.0 compile "com.google.dagger:dagger:$Dagger2_Version" apt "com.google.dagger:dagger-compiler:$Dagger2_Version" // 2. compile 'org.glassfish:javax.annotation:10.0-b28'}
Let's take a look at the Notes 1, 2, and 3 in the gradle. build File.
NOTE 1: The configuration depends on Dagger 2 and the version is 2.0-SNAPSHOT. Compared with the previous version, Dagger is changed from com. square. dagger to com. google. dagger,
Of course this is not the point.
NOTE 2: Why should I add this sentence? Because the @ Generated annotation (described later) is used in Dagger 2, and javax. anotation. generated is available in java 6 and later versions,
There is no Android API, so you must add this sentence in the Android project. If not, the following error is prompted:
error: cannot find symbol class Generatederror: package javax.annotation does not exist
NOTE 3: This is not much. For more information, see http://blog.csdn.net/zjbpku/article/details/22976291. Do not forget to add
apply plugin:android-apt
In the previous Dagger, @ module is a key annotation, which is also indispensable in Dagger 2. The two modules used in this Demo are as follows: (if you have used Dagger, you will not feel that there is a problem)
ActivityModule. java:
/** * Created by zjbpku on 12/20/14. */@Modulepublic class ActivityModule { private Activity mActivity; public ActivityModule(Activity activity) { mActivity = activity; } @Provides Activity providesActivity() { return mActivity; }}
ApplicationModule. java:
/** * Created by zjbpku on 12/20/14. */@Modulepublic class ApplicationModule { Application mApplication; ApplicationModule(Application application) { mApplication = application; } @Provides Application providesApplication() { return mApplication; }}
After writing it, add two @ Component annotation interfaces. This Demo is very simple, just to try to use Dagger 2. Application-related interfaces are actually not needed.
But it must be added in the actual project.
Activityomponent. java:
/** * Created by zjbpku on 12/20/14. */@Component( dependencies = ApplicationComponent.class, modules = ActivityModule.class)public interface ActivityComponent { MainActivity injectActivity(MainActivity activity); ToastHelper getToastHelper(); }
ApplicationComponent. java:
/** * Created by zjbpku on 12/20/14. */@Component( modules = ApplicationModule.class)public interface ApplicationComponent { DaggerApplication injectApplication(DaggerApplication application);}
DaggerApplication. java:
/** * Created by zjbpku on 12/20/14. */public class DaggerApplication extends Application { private ApplicationComponent component; @Override public void onCreate() { super.onCreate(); this.component = Dagger_ApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build(); this.component.injectApplication(this); } ApplicationComponent getComponent() { return this.component; }}
// Add only for test
ToastHelper. java:
/** * Created by zjbpku on 12/22/14. */public class ToastHelper { @Inject ToastHelper() { } //@Inject //Utils utils; Toast toast = null; public void showToast(Context context, CharSequence text) { if (toast == null) { toast = Toast.makeText(context, text, Toast.LENGTH_LONG); } else { toast.setText(text); } toast.show(); } public void show(Context context) { // showToast(context, utils.getContent()); }}
MainActivity. java:
package com.example.zjbpku.dagger2;import android.app.Activity;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity { private ActivityComponent component;// @Inject// ToastHelper toastHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.component = Dagger_ActivityComponent.builder() .applicationComponent(((DaggerApplication) getApplication()).getComponent()) .activityModule(new ActivityModule(this)) .build(); this.component.injectActivity(this); setContentView(R.layout.activity_main); } public void helloDagger2(View v) {// toastHelper.showToast(this, "Dagger 2");// toastHelper.show(this); this.component.getToastHelper().showToast(this, "Dagger 2 Demo"); }}
As you can see, Dagger 2 eliminates all mappings in Dagger 1.x. By adding @ Component, remove ObjectGraph/Injector to make the code clearer.
At this point, the basic usage of Dagger 2 has been completed. In the ActivityComponet interface, you find the getToastHelper () method. In the Mainctivity vity, you can find the ToastHelper annotation of @ Inject.
It is logged out and also logged out in the helloDagger2 (View v) method. This is because the getToastHelper () method does not exist at the beginning and is directly injected through @ Inject in mainctiger.
Later, I read Dagger 2's related materials and found that this is not what Dagger 2 expects. Dagger 2 wants to use the @ Component annotation interface to link the dependency.
This method is now available. In fact, both of them can achieve the same effect, but the code automatically generated by Dagger is different. This will be further introduced later.