Android Dependency Injection: Dagger 2 instance Commentary (i)

Source: Internet
Author: User

This article original, reproduced please indicate the source: Http://blog.csdn.net/zjbpku

[Duplicated] link to Dagger on Android-dagger2 specific explanation

About Dagger, in the previous blog post (Android Dependency injection: Dagger Instance Commentary (demo download)) has been introduced, this article said Dagger 2 is mainly by Google technology

People to participate in the development of. Of course, many of you, including square and some other contributors, have contributed a lot.

The project is probably starting from last November. To the moment the

The Snapshot version was also just announced shortly after the release, from the content provided by GitHub, will soon be the pre release version, then the release version, because

Today is still a preview version, not stable, please use it carefully. The pre release will only be relatively stable. Can be used for project development. I am concerned about this project is still, in advance through a

A demo to introduce Dagger 2.


Dagger 2 is an enhanced version of the Dagger 1.x. In Dagger 1.x, @Inject and @provides annotation form the graph of the object, depending on the dependency between

Relationships and are linked together.

The code can be easily called by a well-defined Atlas set (ObjectGraph).

and in Dagger 2. Such a relationship is replaced by an interface with no method,

The type returned by such a method is the desired type.

The implementation of such an interface is defined by @component annotations and passing in modules parameters. Such as:

@Component (//        dependencies = applicationcomponent.class,        modules = activitymodule.class) public interface activitycomponent {    mainactivity injectactivity (mainactivity activity);    Toasthelper gettoasthelper ();}

At compile time, Dagger 2 will voluntarily generate an implementation of this interface prefixed with Dagger_ dagger_acitvitycomponent. By calling this builder () method to obtain a

instance, by using the builder returned by the 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 ();

Another point, assuming that the method in the interface of the @component annotation has no parameters, a Create () method is generated in the generated instance, and the Create () method is actually
Builder (). build (); this point is mentioned in a later code.

The demo is described below:

The demo uses the latest Androidstudio (hereinafter referred to as) 1.0.2 version number, since using as, there is no Gradle.build file configuration. This project Gradle configuration such as the following:

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:a ndroid-apt:1.4 '//3}}allprojects {repositories {mavencentral () Maven {URL ' Https://oss . sonatype.org/content/repositories/snapshots/'}}}android {compilesdkversion buildtoolsversion "21.1.         2 "Defaultconfig {ApplicationID" com.example.zjbpku.dagger2 "Minsdkversion 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:appcom pat-v7:21.0.3 '//1.Dagger 2.0 Compile "Com.google.dagger:dagger: $Dagger 2_version" apt "Com.google.dagger:dagger-compiler: $Dagger 2_vers    Ion "//2. Compile ' org.glassfish:javax.annotation:10.0-b28 '}
Take a look at the Gradle.build file and stare at 1. 2, 3.

Gaze 1: Is configured to rely on Dagger 2, the version number is 2.0-snapshot, here compared to the previous version number of Dagger is from Com.square.dagger to today's Com.google.dagger,

Of course that's not the point.

Gaze 2: Why add this sentence? Since the @generated annotations (later) are used in Dagger 2, the javax.anotation.generated is in Java 6 and above in the version number,

In the Android API is not, so in the Android project must add this sentence, assuming that there is no hint of the following error:

Error:cannot Find Symbol Class Generatederror:package javax.annotation does not exist

Gaze 3: Not much, detailed function please see http://blog.csdn.net/zjbpku/article/details/22976291, don't forget to add

Apply Plugin:android-apt

In the previous dagger @module is a key note, the same in Dagger 2, the two module used in this demo, such as the following: (used dagger do not think 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, add two @component annotated interface, this demo is very easy. Just to try to use the dagger 2,application related in fact can not, on demo not

What is the impact, but in the actual project still must join, so here also add.

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

Join just to 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, t ext, 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");}    }

Can see. Dagger 2 eliminates all mappings (reflection) in Dagger 1.x, by adding @component. Removing the objectgraph/injector makes the code clearer.

In this way, the basic usage of Dagger 2 has ended, and in the Activitycomponet interface you find the Gettoasthelper () method, @inject in Mainctivity.

is logged off. and is also logged off in the HelloDagger2 (View V) method. This is due to. The Gettoasthelper () method is not at the beginning. Directly injected through @inject directly in the mainctivity.

, and later reading Dagger 2 found that the fact that this is not Dagger 2 expected, Dagger 2 want to use the @component annotation interface to link dependencies, so instead of

The way it is today. In fact both can achieve the same effect. Only the code that dagger itself generates is different, and this will be explained later.




Android Dependency Injection: Dagger 2 instance Commentary (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.