Android Dependency Injection: Dagger 2 Example (i)

Source: Internet
Author: User

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

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

People involved in the development of course, including square and some other contributors, Daniel also contributed a lot. The project is starting from last November, and the current

The Snapshot version was just released shortly after the release, from GitHub, it will soon be the pre release version, then release version, as

This is still a preview version, not stable, please use it carefully, to pre release is relatively stable, can be used for project development. I am concerned about this project is still, in advance through a

A demo to briefly introduce Dagger 2.


Dagger 2 is an enhanced version of the Dagger 1.x, in Dagger 1.x, @Inject and @provides annotation constitute the graph of the object, relying on the dependence between

Relationships and are linked together. A well-defined Atlas (objectgraph) makes it easy to invoke code. In Dagger 2, the relationship is replaced by an interface with no reference method,

The type returned by this method is the desired type. The implementation of this interface is defined by @component annotations and passing in the modules parameter. Such as:

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

At compile time, Dagger 2 automatically generates an implementation of this interface prefixed with Dagger_ dagger_acitvitycomponent. Call this builder () method to get a

instance, by using the builder returned by the method to set other dependencies, build to get a new instance.

This.component = Dagger_activitycomponent.builder ()//                . ApplicationComponent ((daggerapplication) Getapplication ()). Getcomponent ()).                Activitymodule (New Activitymodule (This)).                build ();

Another point, if 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:

Demo uses the latest Androidstudio (hereinafter referred to as) 1.0.2 version, since using as, there is no Gradle.build file configuration, this project Gradle configured 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: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 comments in the Gradle.build file, respectively.

Note 1: Is the configuration Dependent Dagger 2, the version is 2.0-snapshot, here compared to the previous version of Dagger is from Com.square.dagger into the current Com.google.dagger,

Of course that's not the point.

Note 2: Why should I add this sentence? Because @generated annotations (later) are used in Dagger 2, and javax.anotation.generated in Java 6 and later,

In the Android API is not, so in the Android project must add this sentence, if not add the following error is prompted:

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

Note 3: Not much, the specific role please see http://blog.csdn.net/zjbpku/article/details/22976291, don't forget to add

Apply Plugin:android-apt

@module is a key note in the previous dagger, and in Dagger 2, the two module (s) used in this demo are as follows: (used dagger will not feel 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 annotations interface, this demo is very simple, just to try to use Dagger 2,application related actually can not, on the demo will not

What is the impact, but in the actual project still must be added, 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;    }}

Added 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) GetApplicati        On ()). 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 the mappings (reflection) in Dagger 1.x, and by adding @component, removing objectgraph/injector makes the code clearer.

Here, the basic usage of Dagger 2 is over, and in the Activitycomponet interface you find the Gettoasthelper () method, @inject annotation toasthelper in mainctivity

Is logged off, and is also logged off in the HelloDagger2 (View V) method, because the Gettoasthelper () method is not at the beginning, and is injected directly through @inject in mainctivity

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

Now this method. In fact, both can achieve the same effect, but dagger automatically generated code is different, this will be further described.




Android Dependency Injection: Dagger 2 Example (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.