Environment configuration and simple verification of Dagger2 integration

1.1 configuring Dagger2 dependencies

At present, most android applications use gradle for code management, but in the process of integrating Dagger2, there is a certain correlation between the version of gradle and the dependency mode of Dagger2. In some online materials introducing the integration of Dagger2, most of them use "com. Neenbedankt. Gradle. Plugins: android apt: 1.4" as the auxiliary dependency tool of Dagger2, In fact, for the slightly higher gradle, it will be difficult to continue to use apt to connect with Dagger. Moreover, for gradle, it is not recommended to continue to use apt, but to use "annotation processor".

Next, we also use "annotation processor" when configuring the environment.

In the process of code management through gradle, Android projects often use two types of build.gradle files for dependency management, one is project level gradle configuration and the other is app level gradle configuration, which are located under the project root path and the project app path respectively.

Project level build.gradle configuration:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath 'org.greenrobot:eventbus-annotation-processor:3.1.1' //Add dependency annotationProcessor
    }
}
​
allprojects {
    repositories {
        google()
        jcenter()
    }
}
​
task clean(type: Delete) {
    delete rootProject.buildDir
}

Note: focus on the code configuration prompted by comments

app level build.gradle configuration:

apply plugin: 'com.android.application'
​
android {
    compileSdkVersion 30
    buildToolsVersion "31.0.0"
    defaultConfig {
        applicationId "com.tc.app.dagger2"
        minSdkVersion 24
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}
​
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
​
    // Start adding Dagger2 dependencies
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'//Add dependency annotationProcessor
    annotationProcessor 'com.google.dagger:dagger-compiler:2.40'// Specify annotation processor
    compileOnly 'org.glassfish:javax.annotation:10.0-b28'//Add some javax annotations missing from android
    implementation 'com.google.dagger:dagger:2.40'// Specify dependent version
    // Dagger2 dependency addition end
    
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

1.2 simple verification of Dagger2 configuration environment

1.2.1 create a new Android project and configure Dagger2

Create a new simple Android project, and refer to the configuration introduction in Chapter 1.1 to configure the Dagger2 dependency of the project (this process is omitted - it should be done)

1.2.2 writing verification code

First, write the business code (my business API service) waiting for dependency injection

package com.tc.app.dagger2.di;
​
import android.util.Log;
​
/**
 * Real business processing services
 *
 * @author min.weixm
 * @version $Id: MyBusinessApiService.java, v 0.1 2021/11/12 14:35 min.weixm Exp $
 */
public class MyBusinessApiService {
    public void register(){
        Log.i("----------------------------MyBusinessApiService--------------------","MyBusinessApiService");
    }
}

The real business processing class verifies whether the Dagger2 configuration environment can work normally by printing logs.

Next, configure the actual instantiation processing tool (MyBusinessApartModule) of the business processing service

package com.tc.app.dagger2.di;
​
import dagger.Module;
import dagger.Provides;
​
/**
 * Here, instantiate the components that actually perform business processing (for example, instantiate mybusinessapi service)
 *
 * @author min.weixm
 * @version $Id: MyBusinessApartModule.java, v 0.1 2021/11/12 14:38 min.weixm Exp $
 */
@Module
public class MyBusinessApartModule {
    @Provides
    public MyBusinessApiService provideMyBusinessApiService(){
        return new MyBusinessApiService();
    }
​
}

Then, declare our container docking interface (MyApartComponent)

package com.tc.app.dagger2.di;
​
import com.tc.app.dagger2.MainActivity;
​
import dagger.Component;
​
/**
 * The real instance is not provided. The real instance is provided by MyBusinessApartModule
 *
 * @author min.weixm
 * @version $Id: MyApartComponent.java, v 0.1 2021/11/12 14:40 min.weixm Exp $
 */
@Component(modules = {MyBusinessApartModule.class})
public interface MyApartComponent {
    void inject(MainActivity activity);
}

Note: after completing this operation, Dagger2 needs to be awakened for docking business processing and automatic code generation. Therefore, it is necessary to perform a build operation on the project. At this time, Dagger2 will complete the corresponding automatic code generation action

Finally, we do the main activity of dependency injection

package com.tc.app.dagger2;
​
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
​
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
​
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.tc.app.dagger2.di.DaggerMyApartComponent;
import com.tc.app.dagger2.di.MyBusinessApiService;
​
import javax.inject.Inject;
​
public class MainActivity extends AppCompatActivity {
​
    /** Business service instances injected through dependencies */
    @Inject
    MyBusinessApiService myBusinessApiService;
​
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
​
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener((view) ->
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show()
        );
​
        //Initialize the environment and complete the function call
        DaggerMyApartComponent.create().inject(this);
        this.myBusinessApiService.register();
    }
​
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
​
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
​
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
​
        return super.onOptionsItemSelected(item);
    }
}

Verify the results, run the app in the simulator and observe the running log:

I/----------------------------MyBusinessApiService--------------------: MyBusinessApiService
D/OpenGLRenderer: HWUI GL Pipeline
D/: HostConnection::get() New Host Connection established 0xa71e4380, tid 3631
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...

The print log of the business component is successfully obtained, indicating that the Dagger2 configuration verification is successful.

Tags: Android Gradle

Posted on Fri, 12 Nov 2021 05:22:20 -0500 by jcarver