Bhargav
Bhargav

Reputation: 8277

How do I get dagger 2 to work with Android studio java library project

I have an app module (which is my app) and a java library project module (called api) I'd like to use dagger 2 in the api module but the annotation processor is not working, the dagger prefixed classes (ex. DaggerApiComponent) are not being generated like how one would expect. Any help would be greatly appreciated and yes I am using gradle.

Upvotes: 3

Views: 1368

Answers (1)

Bhargav
Bhargav

Reputation: 8277

Finally I managed to fix this, the android-apt plugin for gradle is only available when apply plugin: 'com.android.application' is used. So in a java library where you cannot use the com.android.application plugin you need to instead use the plugin apply plugin: "net.ltgt.apt" after applying this plugin you can use the apt configuration for dagger's compiler dependency apt "com.google.dagger:dagger-compiler:2.0.2" in the dependencies block. Also you need to apply plugin: "idea" for net.ltgt.apt to work correctly, if you don't apply the idea plugin the annotation processor generates the dagger factory classes but it doesn't get included in the IDE's sourceSet, so dont forget to apply the idea plugin. so finally my build script looks like this

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "net.ltgt.gradle:gradle-apt-plugin:0.6"
    }
}
apply plugin: 'java'
apply plugin: "net.ltgt.apt"
apply plugin: "idea"

dependencies {
    // Dagger 2 and Compiler
    compile 'com.google.dagger:dagger:2.0.2'
    apt "com.google.dagger:dagger-compiler:2.0.2"
}

Upvotes: 9

Related Questions