如何在 Gradle 构建过程中从 Avro 模式生成 Java 类?

问题描述 投票:0回答:2

对于 Maven,有一个官方的 Avro 插件可以从 Avro 模式生成 Java 类。

但是,Gradle 没有官方插件。

davidmc24/gradle-avro-plugin,但它不再维护,它正在寻找维护者

如何在 Gradle 构建过程中从 Avro 模式生成 Java 类?

java gradle code-generation avro avro-tools
2个回答
4
投票

我现在创建了一个简单的 Gradle 任务来生成 Avro Java 类。

import org.apache.avro.tool.SpecificCompilerTool

buildscript {
    dependencies {
        // Add the Avro code generation to the build dependencies so that it can be used in a Gradle task.
        classpath group: 'org.apache.avro', name: 'avro-tools', version: '1.11.1'
    }
}

plugins {
    // some project plugins
    id 'application'
}

def avroSchemasDir = "src/main/avro"
def avroCodeGenerationDir = "build/generated-main-avro-java"

// Add the generated Avro Java code to the Gradle source files.
sourceSets.main.java.srcDirs += [avroCodeGenerationDir]

dependencies {
    // some project dependencies
}

tasks.register('avroCodeGeneration') {
    // Define the task inputs and outputs for the Gradle up-to-date checks.
    inputs.dir(avroSchemasDir)
    outputs.dir(avroCodeGenerationDir)
    // The Avro code generation logs to the standard streams. Redirect the standard streams to the Gradle log.
    logging.captureStandardOutput(LogLevel.INFO);
    logging.captureStandardError(LogLevel.ERROR)
    doLast {
        // Run the Avro code generation.
        new SpecificCompilerTool().run(System.in, System.out, System.err, List.of(
                "-encoding", "UTF-8",
                "-string",
                "-fieldVisibility", "private",
                "-noSetters",
                "schema", "$projectDir/$avroSchemasDir".toString(), "$projectDir/$avroCodeGenerationDir".toString()
        ))
    }
}

tasks.withType(JavaCompile).configureEach {
    // Make Java compilation tasks depend on the Avro code generation task.
    dependsOn('avroCodeGeneration')
}

此任务可以添加到任何 Gradle 构建脚本中。


2
投票

插件项目自述文件于 2023 年 12 月更新,声明 Apache Avro 项目正在接管 Gradle 插件。

该项目不再维护。其代码已捐赠给 Apache Avro 项目,该项目将负责处理未来的版本。

因此,将该插件视为官方插件可能是合理的,尽管截至撰写本文时(2023 年 12 月)尚未发布该插件的 Apache Avro 版本。


为了具体回答有关如何从 Gradle 构建生成 Java 类的问题,插件项目自述文件的 usage 部分提供了详细信息和示例:

使用方法

将以下内容添加到您的构建文件中。根据 CHANGES.md 替换所需的版本。

settings.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        mavenCentral()
    }
}

build.gradle

plugins {
    id "com.github.davidmc24.gradle.plugin.avro" version "VERSION"
}

此外,请确保您对 Avro 具有实现依赖性,例如:

repositories {
    mavenCentral()
}
dependencies {
    implementation "org.apache.avro:avro:1.11.0"
}

如果您现在运行

gradle build
,Java 类将从
src/main/avro
中的 Avro 文件编译。 实际上,它会尝试处理每个
SourceSet
中的“avro”目录(主目录、测试目录等)

© www.soinside.com 2019 - 2024. All rights reserved.