1. 程式人生 > >gradle之apt與annotationProcessor

gradle之apt與annotationProcessor

什麼是APT?

隨著一些如ButterKnife,dagger等的開源註解框架的流行,APT的概念也越來越被熟知。

APT(Annotation Processing Tool 的簡稱),可以在程式碼編譯期解析註解,並且生成新的 Java 檔案,減少手動的程式碼輸入。現在有很多主流庫都用上了 APT,比如 Dagger2, ButterKnife, EventBus3 等

DataBinding
Dagger2
ButterKnife
EventBus3
DBFlow
AndroidAnnotation

annotationProcessor和android-apt的功能是一樣的,它們是替代關係。

APT(Annotation Processing Tool)是一種處理註釋的工具,它對原始碼檔案進行檢測找出其中的Annotation,根據註解自動生成程式碼。 Annotation處理器在處理Annotation時可以根據原始檔中的Annotation生成額外的原始檔和其它的檔案(檔案具體內容由Annotation處理器的編寫者決定),APT還會編譯生成的原始檔和原來的原始檔,將它們一起生成class檔案。

Android Gradle外掛2.2版本釋出後,Android 官方提供了annotationProcessor來代替android-apt,annotationProcessor同時支援 javac 和 jack 編譯方式,而android-apt只支援 javac 方式。 同時android-apt作者宣佈不在維護,當然目前android-apt仍然可以正常執行,如果你沒有想支援 jack 編譯方式的話,可以繼續使用 android-apt。

Android Gradle 外掛版本2.2以下:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'		//2.2以下
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'		//apt需要
    }
}

apply plugin: 'com.neenbedankt.android-apt'			//apt需要

dependencies {
	compile 'com.google.dagger:dagger:2.0'
	apt 'com.google.dagger:dagger-compiler:2.0'	//apt
}

Android Gradle 外掛版本升級到 2.2 及以上:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'	//2.2以上
    }
}

dependencies {
    compile 'com.google.dagger:dagger:2.0'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.0'	//annotationProcessor 
}