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:
@Module
Used for classes. The methods of this class provide dependencies.
@Provides
Used
@Module
Methods In annotation classes
@inject
Request dependencies (used in constructors, fields, or methods)
@Component
Is 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
@Module
Annotation class, used for each method that returns Dependencies
@Provides
Annotation. Use on dependent objects
@Inject
Annotation to request dependencies. Use
@Componet
Annotation to create an interface and add
@Module
Annotation class. Create
@Component
Interface 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,Vehicle
AndMotor
.Motor
Is an independent class,Vehicle
Is a dependent class. I plan to startmodel
Create this model.
Motor
The 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 passaccelerate
Andbrake
Method to modify it. And usegetRpm
Method to access the current value.
Vehicle
The 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 createdMotor
Class, 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@Module
Class
Create@Module
Annotation 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 itmodule
Add 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,Vehicle
YesMotor
To 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@Provides
Annotation and the class must have@Module
Annotation.@Singleton
The 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 likeVehicle
YesMotor
In this way, you needVehicle
Added before the constructor@Inject
The Code is as follows:
@Injectpublic Vehicle(Motor motor){ this.motor = motor;}
You can use@Inject
Request dependencies in constructors, fields, and methods. In this example, I use injection in the constructor.
#### Step 4: Use@Inject
Link@Module
Use band@Component
The annotated interface connects to the dependent provider,@Module
And 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();}
@Component
In 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 oneVehicle
Object, so there is only one method.
#### Step 5: Use@Component
Interface to get objects
Now everything is ready. You need to have an interface instance and call its method to obtain the desired object. I willMainActivity
InOnCreate
The 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@Component
You need to useDagger_
Prefix. In this exampleDagger_VehicleComponent
And then usebuilder
To call each module.
The secret lies in the 23rd lines of code. You only needVehicle
Class, 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 displayrpm
Variable Initial ValueToast
Message.
In the related project, you can see a pairMainActivity
Class Custom User interface, which can be modified by clicking the button on the screenrpm
Variable 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.