How to use the Dagger2 series

Source: Internet
Author: User

This series only talk about the use of methods and problems encountered in use, if you still do not know dagger2 children's shoes can refer to the article:

Http://www.jianshu.com/p/cd2c1c9f68d4

http://www.jianshu.com/p/94d47da32656

The premise of using Dagger2 requires adding some dependencies:

1 Add the following to the project build.gradle file

Buildscript {    repositories {        jcenter ()    }    dependencies {         '  com.android.tools.build:gradle:2.1.0'
classpath ' com.neenbedankt.gradle.plugins:android-apt:1.4 '} }

2 Add the following under Module build.gradle

Apply plugin: ' Com.android.application '
Apply plugin: ' Com.neenbedankt.android-apt '
Dependencies {    'com.google.dagger:dagger-compiler:2.4 '      'com.google.dagger:dagger:2.4 '      Org.glassfish:javax.annotation:10.0-b28'}

Let's study the use of Dagger2.

< a > target class and dependent classes are directly modifiable.

1 using @inject annotations on constructors of dependent classes

 Public class needprovide {    @Inject    public  needprovide () {    }    public  void  Printmethod () {        log.d ("dagger.class", " needprovide----Printmethod () " );    }}

2 Create component, as a bridge of target class and dependent class, and be annotated by @component

@Component  Public Interface needcomponent {    void  inject (targetactivity activity);}

3 run, let the project production Xxxcomponent

4 using Xxxcomponent for dependency injection in the target class

Daggerneedcomponent.builder (). Build (). Inject (this);

5 When the dependency injection is complete, the dependent class is used through the @inject

 Public class Targetactivity extends Appcompatactivity {    @Inject    needprovide mneedprovide;    @Override    protectedvoid  onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);       Daggerneedcomponent.builder (). Build (). Inject (  This  );          Mneedprovide.printmethod ();     }}

There are three kinds of characters here. The target class targetactivity, is dependent on the class Needprovide, the bridge needcomponent.

This approach applies to both the target class and the dependent class when we create it ourselves. You cannot add annotations directly to a class constructor when using a third-party library @Inject . Or when a dependent class has multiple constructors, it is not possible to annotate multiple constructors, which creates ambiguity because Dagger2 cannot confirm which constructor is called to generate an instance object of the class. This method is not valid at this point, see the second method below.

< two > Create module provides our dependent classes, using @provides annotation adornments

This method steps the same as above, except that we add some annotations and look directly at the code.

is dependent on the class:

 Public class needprovides {    public  needprovides () {    }    publicvoid  Printmethod () {        log.d ("dagger.class","  Needprovides----Printmethod ()");     }

Here the @inject annotations on the Needprovides class constructor are removed (not removed), here in order to prevent the first method from affecting this one.

The wrapper class for the dependent class is the module:

@Module  Public class providemodules {    @Provides   public  needprovides provideneedprovide () {         return  new  needprovides ();}   }

The use of module encapsulation was previously stated for the purpose of the dependent class. Here we look at this class, the class is decorated with @Module annotations, the method is to provide the dependent class, so with @Provides decoration, the purpose is to let Dagger can find.

@Module  Public class providemodules {    @Provides   public  needprovides provideneedprovide (bean bean) {         return  new  needprovides (bean);   }    @Provides    public  Bean Providebean () {        returnnew  Bean ();    }}

When one of our methods needs parameters, it automatically looks for other methods that are modified by @module annotations.

Bridge:

@Component (modules = providemodules.  Class)publicinterface  needcomponents {    void  inject (Targetactivitys activity);}

The Modules property is used here to specify a wrapper class that encapsulates the dependent class. Component can also rely on multiple module. The next chapter will say.

Target class:

 Public class Targetactivitys extends Appcompatactivity {    @Inject    needprovides mneedprovides;    @Override    protectedvoid  onCreate (Bundle savedinstancestate) {        super.oncreate ( Savedinstancestate);        Setcontentview (r.layout.activity_main);        Daggerneedcomponents.builder (). Build (). Inject (this);         Mneedprovides.printmethod ();     }}

Above we introduced the two methods used by Dagger2, if both methods are used in the actual situation, then which method will be used to create the real column by default? In fact, when building class instances, they are executed in the following order:

Find the class instance creation method from module

    1. There is a creation method in module, see if this method has parameters
      1. If there are parameters, these parameters are also provided by component, return to Step 1 to generate an instance of the parameter class, and finally generate the final class instance
      2. If there are no parameters, the final class instance is generated directly from this method
    2. There is no method created in module, find the constructor with @inject annotation from inside the constructor
      1. If the constructor has parameters, it is also returned to Step 1 to generate the argument class instance, and finally call the constructor to generate the class instance
      2. If the constructor has no arguments, call the constructor directly to generate the class instance

This is the build step to inject the generated class instance one at a time. (copy others, original link: http://www.jianshu.com/p/94d47da32656)

Dagger2 the most basic method of use has been introduced, the next time I will explain my actual use of the problems encountered.

How to use the Dagger2 series

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.