DI 101 — Part 4

Dependency Injection for the Android platform

Roberto Orgiu
DI 101

--

In the previous articles of this series, we explored what Scopes are and how we can use them to have a finer control on our dependencies’ lifecycle. In the meanwhile, things have changed and it’s now time to upgrade Dagger and the plugins we use.

Farewell Android APT, welcome Android Plugin

One of the first steps in order to use Dagger was to import the android-apt plugin from Hugo Visser. As of Android Plugin for Gradle 2.2.0, we don’t need it any more: the new annotationProcessor provided by the Tools team is providing the same functionalities and it works with Jack and Jill as well.

The first thing we have to do is to ensure that we are using at least the version 2.2.0 of the Gradle plugin (at the time of writing, the latest stable version available is 2.2.3).

This means we’ll have in our root build.gradle file a line that looks like this:

classpath 'com.android.tools.build:gradle:2.2.3'

Right after this, we shall delete the android-apt class path, since we don’t need it any more; so we look for this line and erase it:

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

At this point, we head towards the build.gradle in which we declared the Dagger dependencies and delete the following plugin line:

apply plugin: 'com.neenbedankt.android-apt'

The last thing we have to do is replacing all the occurrences of the apt directive with the new annotationProcessor one, so that our lines go from something like

apt 'com.google.dagger:dagger-compiler:2.6'

to this

annotationProcessor 'com.google.dagger:dagger-compiler:2.6'

What could possibly go wrong?

The steps to replace the Android APT plugin are fairly easy, but things can go south quickly if you are using libraries that include the plugin itself: in this case, annotationProcessor won’t work and you won’t be able to compile your project as the Components won’t be generated.

Personally, I encounter this issue with the Realm dependency, that was stuck in my project at 1.1.1: as until 2.2.0 it was in fact using the Android APT plugin, compiler kept on crashing as my android-apt implementation was clashing with the annotation processor declaration.

Luckily, starting from version 2.2.0, Realm team dismissed the Android APT plugin in favour of the annotationProcessor directive (while it still uses kapt if you are using Kotlin), making the migration process much easier.

Conclusion

The annotation processor support added in the latest version of the tools certainly is a good step to take, but the news about Dagger aren’t over yet, as much have changed in version 2.7. Stay tuned for scenes from the next episode…

--

--

Roberto Orgiu
DI 101

Developer Relations Engineer, Android @ Google