주석 프로세서 추가

이 페이지에는 주석 프로세서를 프로젝트 종속 항목으로 추가하고 구성하는 방법에 관한 자세한 안내가 포함되어 있습니다. 주석 프로세서에 관한 자세한 내용은 종속 항목 구성 항목을 참고하세요.

컴파일 클래스 경로에 주석 프로세서를 추가하면 다음과 유사한 오류 메시지가 표시됩니다.

Error: Annotation processors must be explicitly declared now.

이 오류를 해결하려면 아래와 같이 annotationProcessor를 사용하여 종속 항목을 구성하고 프로젝트에 주석 프로세서를 추가하세요.

Kotlin

dependencies {
    // Adds libraries defining annotations to only the compile classpath.
    compileOnly("com.google.dagger:dagger:version-number")
    // Adds the annotation processor dependency to the annotation processor classpath.
    annotationProcessor("com.google.dagger:dagger-compiler:version-number")
}

Groovy

dependencies {
    // Adds libraries defining annotations to only the compile classpath.
    compileOnly 'com.google.dagger:dagger:version-number'
    // Adds the annotation processor dependency to the annotation processor classpath.
    annotationProcessor 'com.google.dagger:dagger-compiler:version-number'
}

참고:Gradle용 Android 플러그인 3.0.0 이상에서는 더 이상 android-apt 플러그인이 지원되지 않습니다.

주석 프로세서에 인수 전달

주석 프로세서에 인수를 전달해야 하는 경우 모듈의 빌드 구성에서 AnnotationProcessorOptions 블록을 사용하여 전달하면 됩니다. 예를 들어 프리미티브 데이터 유형을 키-값 쌍으로 전달하려면 아래와 같이 argument 속성을 사용하면 됩니다.

Kotlin

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += mapOf("key1" to "value1",
                                   "key2" to "value2")
            }
        }
    }
}

Groovy

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                argument 'key1', 'value1'
                argument 'key2', 'value2'
            }
        }
    }
}

그러나 Android Gradle 플러그인 3.2.0 이상을 사용하는 경우 Gradle의 CommandLineArgumentProvider 인터페이스를 사용하여 파일이나 디렉터리를 나타내는 프로세서 인수를 전달해야 합니다.

CommandLineArgumentProvider를 사용하면 개발자 또는 주석 프로세서 작성자가 각 인수에 증분 빌드 속성 유형 주석을 적용하여 증분 및 캐시된 클린 빌드의 정확성과 성능을 개선할 수 있습니다.

예를 들어 아래의 클래스에는 CommandLineArgumentProvider를 구현하고 프로세서의 각 인수에 주석을 추가합니다.

Kotlin

class MyArgsProvider(
    // Annotates each directory as either an input or output for the
    // annotation processor.
    @get:InputFiles
    // Using this annotation helps Gradle determine which part of the file path
    // should be considered during up-to-date checks.
    @get:PathSensitive(PathSensitivity.RELATIVE)
    val inputDir: FileCollection,

    @get:OutputDirectory
    val outputDir: File
) : CommandLineArgumentProvider {
    // Specifies each directory as a command line argument for the processor.
    // The Android plugin uses this method to pass the arguments to the
    // annotation processor.

    override fun asArguments(): Iterable<String> {
        // Use the form '-Akey[=value]' to pass your options to the Java compiler.
        return listOf("-AinputDir=${inputDir.singleFile.absolutePath}",
                      "-AoutputDir=${outputDir.absolutePath}")
    }
}

android {...}

Groovy

class MyArgsProvider implements CommandLineArgumentProvider {

    // Annotates each directory as either an input or output for the
    // annotation processor.
    @InputFiles
    // Using this annotation helps Gradle determine which part of the file path
    // should be considered during up-to-date checks.
    @PathSensitive(PathSensitivity.RELATIVE)
    FileCollection inputDir

    @OutputDirectory
    File outputDir

    // The class constructor sets the paths for the input and output directories.
    MyArgsProvider(FileCollection input, File output) {
        inputDir = input
        outputDir = output
    }

    // Specifies each directory as a command line argument for the processor.
    // The Android plugin uses this method to pass the arguments to the
    // annotation processor.
    @Override
    Iterable<String> asArguments() {
        // Use the form '-Akey[=value]' to pass your options to the Java compiler.
        ["-AinputDir=${inputDir.singleFile.absolutePath}",
         "-AoutputDir=${outputDir.absolutePath}"]
    }
}

android {...}

CommandLineArgumentProvider를 구현하는 클래스를 정의한 후에는 아래와 같이 annotationProcessorOptions.compilerArgumentProvider 메서드를 사용하여 인스턴스를 만들고 Android 플러그인에 전달해야 합니다.

Kotlin

// This is in your module's build.gradle file.
android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                // Creates a new MyArgsProvider object, specifies the input and
                // output paths for the constructor, and passes the object
                // to the Android plugin.
                compilerArgumentProvider(MyArgsProvider(files("input/path"),
                                                          file("output/path")))
            }
        }
    }
}

Groovy

// This is in your module's build.gradle file.
android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                // Creates a new MyArgsProvider object, specifies the input and
                // output paths for the constructor, and passes the object
                // to the Android plugin.
                compilerArgumentProvider new MyArgsProvider(files("input/path"),
                                         new File("output/path"))
            }
        }
    }
}

CommandLineArgumentProvider 구현을 통해 빌드 성능을 개선하는 방법에 관한 자세한 내용은 자바 프로젝트 캐싱을 참고하세요.

주석 프로세서 오류 검사 중지

불필요한 주석 프로세서가 포함된 종속 항목이 컴파일 클래스 경로에 있는 경우 다음을 build.gradle.kts 파일에 추가하여 오류 검사를 중지할 수 있습니다. 컴파일 클래스 경로에 주석 프로세서를 추가해도 프로세서 클래스 경로에는 추가되지 않습니다.

Kotlin

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                argument("includeCompileClasspath", "false")
            }
        }
    }
}

Groovy

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath false
            }
        }
    }
}

Kotlin과 kapt를 사용하는 경우:

Kotlin

android {
    ...
    defaultConfig {
        ...
        kapt {
            includeCompileClasspath = false
        }
    }
}

Groovy

android {
    ...
    defaultConfig {
        ...
        kapt {
            includeCompileClasspath false
        }
    }
}

프로젝트의 주석 프로세서를 프로세서 클래스 경로로 이전한 후 문제가 발생하면 includeCompileClasspathtrue로 설정하여 컴파일 클래스 경로의 주석 프로세서를 허용할 수 있습니다. 그러나 이 속성을 true로 설정하는 것은 권장되지 않으며 이렇게 하는 옵션은 향후 Android 플러그인 업데이트에서 삭제될 예정입니다.