Android project uses Dagger2 for dependency Injection

Source: Internet
Author: User
Tags sonatype

Android project uses Dagger2 for dependency Injection

Link: http://code.tutsplus.com/tutorials/dependency-injection-with-dagger-2-on-android-cms-23345

Dependency injection is a software design model designed for loose coupling, scalability, and maintainability of applications. In this tutorial, you will learn how to use Dagger2 for dependency injection.

Introduction

This is a dependency when an object needs to be processed or relies on other objects. Dependency can be solved by creating dependent objects or creating a dependent object using the factory method. In the case of dependency injection, however, the dependency provided to the class must be avoided from the class to create them. In this way, the software you created is loosely coupled and highly maintainable.

This tutorial uses the latest Dagger version, Dagger 2. During the writing, Dagger 2 has not yet been officially released and is in the pre-alpha stage. However, it is available and stable. You can visit Dagger on GitHub to get the project news and the release date of the official version.

Prerequisites

You need to install the latest Android Studio on the development machine, which can be downloaded from the Android developer website.

Dagger 2 API

Dagger 2 provides some special annotations:

@ModuleUsed for classes. The methods of this class provide dependencies. @ProvidesUsed @ModuleMethods In annotation classes @injectRequest dependencies (used in constructors, fields, or methods) @ComponentIs the interface between the module and the injection

These are the important notes that you need to know about using Dagger 2 for dependency injection. I will show you how to use them in a simple Android app.

Dagger 2 Workflow

To use Dagger 2 properly, follow these steps:

Identify the dependent object and its dependencies. Create a tape @ModuleAnnotation class, used for each method that returns Dependencies @ProvidesAnnotation. Use on dependent objects @InjectAnnotation to request dependencies. Use @ComponetAnnotation to create an interface and add @ModuleAnnotation class. Create @ComponentInterface object to instantiate dependent objects that come with dependencies.

Dependency analysis is converted from runtime to compilation. This means that you can know the possible problems in the development phase, rather than other libraries, such as Guice. Before using the Dagger 2 library, you need to install Android Stuido to access the generated class.

Step 1 in the Android Studio Environment

Use Android Studio to create and name a new application. My project is namedTutsplusDagger.

Step 2

Set the project'sMinimum SDK versionIsAPI 10To adapt to more models.

Step 3

Select created activityNullLayout. No special layout is required for this tutorial.

Step 4

Name activity as Main
Activity and clickFinishButton.

After the project is created, you need to modify the gradle file. Let's make these changes in the next step.

Configure Gradle settings. Step 1

We need to modify the project'sBuild. gradleThe file is as follows:

buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:1.0.0'        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'    }}allprojects {    repositories {        mavenCentral()        maven{            url 'https://oss.sonatype.org/content/repositories/snapshots/'        }    }}

Let's take a look at the changes:
-Dependencies: In this section, I added a plug-in that will be used to access the files generated by Dagger. If you do not add these new classes, you will see an error when accessing these new classes.
-Allprojects: This modification is because the library we use is currently in the pre-alpha stage, and this is the unique available address for accessing the library using Maven. You can also download the Dagger and Dagger compiler libraries from Sonatype, but this tutorial is based on the Maven repository.

#### Step 2
Open the project app folderBuild. gradleFile, modify as follows:

apply plugin: 'com.android.application'apply plugin: 'com.neenbedankt.android-apt'android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig {     applicationId "com.androidheroes.tutsplusdagger"     minSdkVersion 10     targetSdkVersion 21     versionCode 1     versionName "1.0" } buildTypes {     release {         minifyEnabled false         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'     } }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' compile 'com.google.dagger:dagger:2.0-SNAPSHOT' apt 'com.google.dagger:dagger-compiler:2.0-SNAPSHOT' provided 'org.glassfish:javax.annotation:10.0-b28'}

At the beginning of the file, I applied a new plug-in. Make sure that the new plug-in (Com. neenbedankt. android-aptAfter the Android plug-in. If this is not done, an error will be displayed when synchronizing the gradle file of the project.

InDependenciesAdded the following dependencies:
-DaggerLibrary
-Dagger-compilerUsed for code generation
-Javax. annotationAdditional annotations for requirements other than Dagger

After updating the configuration of Dagger, you need to click the button above to synchronize the gradle file of the project.

By now, your application has an empty project ready for use. If any error occurs, make sure that you follow the above steps correctly. Now let's implement our chestnut project.

Implement Dagger 2 Step 1: Identify dependent objects

In this tutorial, I plan to implement two classes,VehicleAndMotor.MotorIs an independent class,VehicleIs a dependent class. I plan to startmodelCreate this model.

MotorThe class structure is as follows:

package com.androidheroes.tutsplusdagger.model;/*** Created by kerry on 14/02/15.*/public class Motor {   private int rpm;   public Motor(){       this.rpm = 0;   }   public int getRpm(){       return rpm;   }   public void accelerate(int value){       rpm = rpm + value;   }   public void brake(){       rpm = 0;   }}

This class has only onermp, I'm going to passaccelerateAndbrakeMethod to modify it. And usegetRpmMethod to access the current value.

VehicleThe class structure is as follows:

package com.androidheroes.tutsplusdagger.model;/*** Created by kerry on 14/02/15.*/public class Vehicle {   private Motor motor;   public Vehicle(Motor motor){       this.motor = motor;   }   public void increaseSpeed(int value){       motor.accelerate(value);   }   public void stop(){       motor.brake();   }   public int getSpeed(){       return motor.getRpm();   }}

In the class, you can see that I have not createdMotorClass, even if its method is used. In real-world applications, this class should have more methods and attributes, but keep it as simple as possible.

#### Step 2: Create@ModuleClass

Create@ModuleAnnotation class. This class provides built-in dependent objects. Because of this, you need to create a new package name (just to maintain the order) and name itmoduleAdd a new class in it. The Code is as follows:

package com.androidheroes.tutsplusdagger.module;import com.androidheroes.tutsplusdagger.model.Motor;import com.androidheroes.tutsplusdagger.model.Vehicle;import javax.inject.Singleton;import dagger.Module;import dagger.Provides;/*** Created by kerry on 14/02/15.*/@Modulepublic class VehicleModule {   @Provides @Singleton   Motor provideMotor(){       return new Motor();   }   @Provides @Singleton   Vehicle provideVehicle(){       return new Vehicle(new Motor());   }}

InStep 1I pointed out,VehicleYesMotorTo work normally. This is why you need to create two providers, oneMotor(Independent Model ).Vehicle(Specify its Dependencies ).

Do not forget that each provider (or method) must be added@ProvidesAnnotation and the class must have@ModuleAnnotation.@SingletonThe annotation specifies that the object can only have one instance.

#### Step 3: Request dependency in the dependent object

Different models now have providers. You need to request them. Just likeVehicleYesMotorIn this way, you needVehicleAdded before the constructor@InjectThe Code is as follows:

@Injectpublic Vehicle(Motor motor){   this.motor = motor;}

You can use@InjectRequest dependencies in constructors, fields, and methods. In this example, I use injection in the constructor.

#### Step 4: Use@InjectLink@Module

Use band@ComponentThe annotated interface connects to the dependent provider,@ModuleAnd request their classes. These classes are marked@Inject

package com.androidheroes.tutsplusdagger.component;import com.androidheroes.tutsplusdagger.model.Vehicle;import com.androidheroes.tutsplusdagger.module.VehicleModule;import javax.inject.Singleton;import dagger.Component;/** * Created by kerry on 14/02/15. */@Singleton@Component(modules = {VehicleModule.class})public interface VehicleComponent {    Vehicle provideVehicle();}

@ComponentIn the annotation, You need to specify the class to be used-this example isVehicleModule. If you want to use more modules, you only need to use commas as separators to add them.

Interface, add a method to each required object, they will automatically add dependencies. In this example, only oneVehicleObject, so there is only one method.

#### Step 5: Use@ComponentInterface to get objects

Now everything is ready. You need to have an interface instance and call its method to obtain the desired object. I willMainActivityInOnCreateThe Code is as follows:

package com.androidheroes.tutsplusdagger;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.widget.Toast;import com.androidheroes.tutsplusdagger.component.Dagger_VehicleComponent;import com.androidheroes.tutsplusdagger.component.VehicleComponent;import com.androidheroes.tutsplusdagger.model.Vehicle;import com.androidheroes.tutsplusdagger.module.VehicleModule;public class MainActivity extends ActionBarActivity {Vehicle vehicle;@Overrideprotected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   VehicleComponent component = Dagger_VehicleComponent.builder().vehicleModule(new VehicleModule()).build();   vehicle = component.provideVehicle();   Toast.makeText(this, String.valueOf(vehicle.getSpeed()), Toast.LENGTH_SHORT).show();}

When you plan to create@ComponentYou need to useDagger_ Prefix. In this exampleDagger_VehicleComponentAnd then usebuilderTo call each module.

The secret lies in the 23rd lines of code. You only needVehicleClass, the Dagger2 library is responsible for preparing all the dependencies of this object. Similarly, you cannot see any new instance of any other object-The Dagger2 library helps you process all.

You can now run applications on devices or simulators. If you follow the step-by-step implementation of the tutorial, you will see a displayrpmVariable Initial ValueToastMessage.

In the related project, you can see a pairMainActivityClass Custom User interface, which can be modified by clicking the button on the screenrpmVariable value.

Conclusion

Dependency injection is a mode that will be used in your application sooner or later. With Dagger 2, you have a powerful tool for implementing dependency injection. I hope this tutorial will be useful to you. If you like it, please share it.

Related Article

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.