Thêm trình xử lý chú thích

Trang này cung cấp hướng dẫn chi tiết về cách thêm và định cấu hình trình xử lý chú giải làm phần phụ thuộc của dự án. Để tìm hiểu thêm về trình xử lý chú giải, hãy xem mục nhập trong phần Định cấu hình phần phụ thuộc.

Nếu thêm trình xử lý chú thích vào đường dẫn lớp biên dịch, một thông báo lỗi như sau sẽ xuất hiện:

Error: Annotation processors must be explicitly declared now.

Để khắc phục lỗi này, hãy thêm trình xử lý chú thích vào dự án bằng cách định cấu hình phần phụ thuộc bằng cách sử dụng annotationProcessor như đoạn mã bên dưới:

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'
}

Lưu ý: Trình bổ trợ Android cho Gradle phiên bản 3.0.0 trở lên không còn hỗ trợ trình bổ trợ android-apt.

Chuyển đối số đến trình xử lý chú thích

Nếu cần chuyển các đối số đến trình xử lý chú thích, bạn có thể sử dụng khối AnnotationProcessorOptions trong cấu hình bản dựng của mô-đun. Chẳng hạn, nếu muốn chuyển các kiểu dữ liệu chính làm cặp khoá-giá trị, bạn có thể sử dụng thuộc tính argument, như minh hoạ bên dưới:

Kotlin

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

Groovy

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

Tuy nhiên, khi sử dụng Trình bổ trợ Android cho Gradle phiên bản 3.2.0 trở lên, bạn cần phải chuyển các đối số trình xử lý đại diện cho các tệp hoặc thư mục bằng cách sử dụng giao diện CommandLineArgumentProvider của Gradle.

Việc sử dụng CommandLineArgumentProvider cho phép bạn hoặc tác giả của trình xử lý chú giải có thể cải thiện độ chính xác và hiệu suất của các bản dựng sạch gia tăng và lưu vào bộ nhớ đệm bằng cách áp dụng các chú giải kiểu thuộc tính bản dựng gia tăng cho mỗi đối số.

Chẳng hạn, lớp bên dưới triển khai CommandLineArgumentProvider và chú thích từng đối số cho trình xử lý.

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 {...}

Sau khi khai báo một lớp triển khai CommandLineArgumentProvider, bạn cần tạo một thực thể và chuyển thực thể đó tới trình bổ trợ Android bằng cách sử dụng phương thức annotationProcessorOptions.compilerArgumentProvider, như ở đoạn mã bên dưới.

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"))
            }
        }
    }
}

Để tìm hiểu thêm về lợi ích của việc triển khai CommandLineArgumentProvider đối với hiệu năng của bản dựng, hãy đọc bài viết Lưu các dự án Java vào bộ đệm.

Tắt tính năng kiểm tra lỗi của trình xử lý chú thích

Nếu bạn có các phần phụ thuộc trên đường dẫn lớp biên dịch chứa các trình xử lý chú thích không cần thiết, bạn có thể tắt tính năng kiểm tra lỗi bằng cách thêm nội dung sau vào tệp build.gradle.kts. Luôn nhớ rằng các trình xử lý chú thích mà bạn thêm vào đường dẫn lớp biên dịch vẫn chưa được thêm vào đường dẫn lớp của bộ xử lý.

Kotlin

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

Groovy

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

Nếu sử dụng Kotlin và kapt:

Kotlin

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

Groovy

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

Nếu gặp sự cố sau khi di chuyển trình xử lý chú giải của dự án sang classpath trình xử lý, bạn có thể đặt includeCompileClasspath thành true để cho phép trình xử lý chú giải trên classpath biên dịch. Tuy nhiên, bạn không nên thiết lập thuộc tính này thành true, và tuỳ chọn này sẽ bị xoá trong bản cập nhật trình bổ trợ Android sắp tới.