Skip to content

KSP 快速入門

若要快速開始,您可以建立自己的處理器 (processor) 或取得一個範例處理器

新增處理器

若要新增處理器,您需要包含 KSP Gradle 外掛程式 (Plugin) 並新增對該處理器的依賴項 (dependency):

  1. 將 KSP Gradle 外掛程式 com.google.devtools.ksp 新增到您的 build.gradle(.kts) 檔案:

    kotlin
    plugins {
        id("com.google.devtools.ksp") version "2.2.0-2.0.2"
    }
    groovy
    plugins {
        id 'com.google.devtools.ksp' version '2.2.0-2.0.2'
    }
  2. 新增對該處理器的依賴項。 此範例使用 Dagger。請將其替換為您想要新增的處理器。

    kotlin
    dependencies {
        implementation("com.google.dagger:dagger-compiler:2.51.1")
        ksp("com.google.dagger:dagger-compiler:2.51.1")
    }
    groovy
    dependencies {
        implementation 'com.google.dagger:dagger-compiler:2.51.1'
        ksp 'com.google.dagger:dagger-compiler:2.51.1'
    }
  3. 執行 ./gradlew build。您可以在 build/generated/ksp 目錄中找到生成的程式碼。

以下是一個完整的範例:

kotlin
plugins {
    id("com.google.devtools.ksp") version "2.2.0-2.0.2"
    kotlin("jvm")
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation("com.google.dagger:dagger-compiler:2.51.1")
    ksp("com.google.dagger:dagger-compiler:2.51.1")
}
groovy
plugins {
    id 'com.google.devtools.ksp' version '2.2.0-2.0.2'
    id 'org.jetbrains.kotlin.jvm' version '2.2.10'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.10'
    implementation 'com.google.dagger:dagger-compiler:2.51.1'
    ksp 'com.google.dagger:dagger-compiler:2.51.1'
}

建立您自己的處理器

  1. 建立一個空的 Gradle 專案。

  2. 在根專案中指定 Kotlin 外掛程式的 2.2.0 版本,以供其他專案模組使用:

    kotlin
    plugins {
        kotlin("jvm") version "2.2.0" apply false
    }
    
    buildscript {
        dependencies {
            classpath(kotlin("gradle-plugin", version = "2.2.0"))
        }
    }
    groovy
    plugins {
        id 'org.jetbrains.kotlin.jvm' version '2.2.0' apply false
    }
    
    buildscript {
        dependencies {
            classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.0'
        }
    }
  3. 新增一個用於託管處理器的模組。

  4. 在該模組的建置腳本中,套用 Kotlin 外掛程式並將 KSP API 新增到 dependencies 區塊。

    kotlin
    plugins {
        kotlin("jvm")
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation("com.google.devtools.ksp:symbol-processing-api:2.2.0-2.0.2")
    }
    groovy
    plugins {
        id 'org.jetbrains.kotlin.jvm' version '2.2.10'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.devtools.ksp:symbol-processing-api:2.2.0-2.0.2'
    }
  5. 您需要實作 com.google.devtools.ksp.processing.SymbolProcessorcom.google.devtools.ksp.processing.SymbolProcessorProvider。 您對 SymbolProcessorProvider 的實作將作為一項服務載入,以實例化您所實作的 SymbolProcessor。 請注意以下事項:

    • 實作 SymbolProcessorProvider.create() 以建立 SymbolProcessor。透過 SymbolProcessorProvider.create() 的參數傳遞您的處理器所需的依賴項 (例如 CodeGenerator、處理器選項)。
    • 您的主要邏輯應位於 SymbolProcessor.process() 方法中。
    • 使用 resolver.getSymbolsWithAnnotation() 取得您想要處理的符號,並提供註解 (annotation) 的完整合格名稱。
    • KSP 的一個常見用例是實作一個客製化的訪問器 (visitor) (介面 com.google.devtools.ksp.symbol.KSVisitor) 以操作符號。一個簡單的範本訪問器是 com.google.devtools.ksp.symbol.KSDefaultVisitor
    • 如需 SymbolProcessorProviderSymbolProcessor 介面的範例實作,請參閱範例專案中的以下檔案。
      • src/main/kotlin/BuilderProcessor.kt
      • src/main/kotlin/TestProcessor.kt
    • 編寫您自己的處理器後,透過在 src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider 中包含其完整合格名稱,將您的處理器提供者註冊到套件。

在專案中使用您自己的處理器

  1. 建立另一個模組,其中包含您想要試用處理器的工作負載。

    kotlin
    pluginManagement { 
        repositories { 
            gradlePluginPortal()
        }
    }
    groovy
    pluginManagement {
        repositories {
            gradlePluginPortal()
        }
    }
  2. 在該模組的建置腳本中,套用指定版本的 com.google.devtools.ksp 外掛程式,並將您的處理器新增到依賴項清單。

    kotlin
    plugins {
        id("com.google.devtools.ksp") version "2.2.0-2.0.2"
    }
    
    dependencies {
        implementation(kotlin("stdlib-jdk8"))
        implementation(project(":test-processor"))
        ksp(project(":test-processor"))
    }
    groovy
    plugins {
        id 'com.google.devtools.ksp' version '2.2.0-2.0.2'
    }
    
    dependencies {
        implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.10'
        implementation project(':test-processor')
        ksp project(':test-processor')
    }
  3. 執行 ./gradlew build。您可以在 build/generated/ksp 下找到生成的程式碼。

以下是將 KSP 外掛程式套用到工作負載的範例建置腳本:

kotlin
plugins {
    id("com.google.devtools.ksp") version "2.2.0-2.0.2"
    kotlin("jvm") 
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation(project(":test-processor"))
    ksp(project(":test-processor"))
}
groovy
plugins {
    id 'com.google.devtools.ksp' version '2.2.0-2.0.2'
    id 'org.jetbrains.kotlin.jvm' version '2.2.10'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.jetbrains.kotlin:kotlin-stdlib:2.2.10'
    implementation project(':test-processor')
    ksp project(':test-processor')
}

將選項傳遞給處理器

SymbolProcessorEnvironment.options 中的處理器選項在 Gradle 建置腳本中指定:

none
ksp {
    arg("option1", "value1")
    arg("option2", "value2")
    ...
}

讓 IDE 了解生成的程式碼

生成的原始碼檔案自 KSP 1.8.0-1.0.9 起已自動註冊。 如果您使用的是 KSP 1.0.9 或更高版本,並且不需要讓 IDE 了解生成的資源, 請隨意跳過本節。

預設情況下,IntelliJ IDEA 或其他 IDE 不了解生成的程式碼。因此,它會將對生成的符號的引用標記為無法解析。為了讓 IDE 能夠理解生成的符號,請將以下路徑標記為生成的原始碼根目錄:

text
build/generated/ksp/main/kotlin/
build/generated/ksp/main/java/

如果您的 IDE 支援資源目錄,也請標記以下目錄:

text
build/generated/ksp/main/resources/

也可能需要在您的 KSP 消費者模組的建置腳本中配置這些目錄:

kotlin
kotlin {
    sourceSets.main {
        kotlin.srcDir("build/generated/ksp/main/kotlin")
    }
    sourceSets.test {
        kotlin.srcDir("build/generated/ksp/test/kotlin")
    }
}
groovy
kotlin {
    sourceSets {
        main.kotlin.srcDirs += 'build/generated/ksp/main/kotlin'
        test.kotlin.srcDirs += 'build/generated/ksp/test/kotlin'
    }
}

如果您在 Gradle 外掛程式中同時使用 IntelliJ IDEA 和 KSP,那麼上述程式碼片段將會產生以下警告:

text
Execution optimizations have been disabled for task ':publishPluginJar' to ensure correctness due to the following reasons:
Gradle detected a problem with the following location: '../build/generated/ksp/main/kotlin'. 
Reason: Task ':publishPluginJar' uses this output of task ':kspKotlin' without declaring an explicit or implicit dependency.

在這種情況下,請改用以下腳本:

kotlin
plugins {
    // ...
    idea
}

idea {
    module {
        // Not using += due to https://github.com/gradle/gradle/issues/8749
        sourceDirs = sourceDirs + file("build/generated/ksp/main/kotlin") // or tasks["kspKotlin"].destination
        testSourceDirs = testSourceDirs + file("build/generated/ksp/test/kotlin")
        generatedSourceDirs = generatedSourceDirs + file("build/generated/ksp/main/kotlin") + file("build/generated/ksp/test/kotlin")
    }
}
groovy
plugins {
    // ...
    id 'idea'
}

idea {
    module {
        // Not using += due to https://github.com/gradle/gradle/issues/8749
        sourceDirs = sourceDirs + file('build/generated/ksp/main/kotlin') // or tasks["kspKotlin"].destination
        testSourceDirs = testSourceDirs + file('build/generated/ksp/test/kotlin')
        generatedSourceDirs = generatedSourceDirs + file('build/generated/ksp/main/kotlin') + file('build/generated/ksp/test/kotlin')
    }
}