You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为avro-maven-plugin生成的Java类字段添加@JsonProperty注解?

解决Avro Maven插件生成Java类时添加@JsonProperty注解的问题

核心思路

Avro默认模板不支持直接给字段添加自定义注解,需要通过修改Velocity模板或利用Avro自定义属性扩展实现。以下是两种可行方案:


方案一:修改record.vm模板(推荐)

  1. 提取并复制默认模板
    从avro-tools包中取出默认的record.vm模板(路径:org/apache/avro/compiler/specific/templates/java/record.vm),放到项目的src/main/resources/avro/templates目录下。

  2. 修改模板添加注解逻辑
    在模板的字段定义区域,加入判断逻辑:若字段自定义属性包含JsonProperty,则生成对应注解。示例修改片段:

    #foreach ($field in $fields)
      #if ($field.javaAnnotation)
      @$field.javaAnnotation
      #end
      #if ($field.props.containsKey("JsonProperty"))
      @JsonProperty("$field.props.get('JsonProperty')")
      #end
      private $field.type $field.name;
    #end
    
  3. 配置pom.xml指定自定义模板
    在avro-maven-plugin的配置里添加模板路径:

    <plugin>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro-maven-plugin</artifactId>
      <version>1.11.3</version>
      <executions>
        <execution>
          <phase>generate-sources</phase>
          <goals>
            <goal>schema</goal>
          </goals>
          <configuration>
            <sourceDirectory>${project.basedir}/src/main/resources/avro</sourceDirectory>
            <outputDirectory>${project.build.directory}/generated-sources/avro</outputDirectory>
            <!-- 指定自定义模板路径 -->
            <templateDirectory>${project.basedir}/src/main/resources/avro/templates</templateDirectory>
          </configuration>
        </execution>
      </executions>
    </plugin>
    
  4. 在AVSC文件中添加自定义属性
    给需要加注解的字段添加JsonProperty属性:

    {
      "type": "record",
      "name": "User",
      "fields": [
        {"name": "userId", "type": "string", "JsonProperty": "user_id"},
        {"name": "userName", "type": "string"}
      ]
    }
    

方案二:使用Avro的javaAnnotation扩展(兼容默认模板)

如果不想修改模板,可直接在AVSC字段中使用javaAnnotation属性,注意格式要完整:

{
  "type": "record",
  "name": "User",
  "fields": [
    {
      "name": "userId",
      "type": "string",
      "javaAnnotation": "@com.fasterxml.jackson.annotation.JsonProperty(\"user_id\")"
    },
    {"name": "userName", "type": "string"}
  ]
}

默认的record.vm会直接将javaAnnotation字段的内容渲染到生成的代码中。


注意事项

  • 确保项目引入Jackson依赖:
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.2</version>
    </dependency>
    
  • 修改模板后,执行mvn clean generate-sources重新生成代码。
  • 方案一中的自定义模板需和Avro版本兼容,避免版本升级导致语法不匹配。

内容的提问来源于stack exchange,提问作者Abhishek Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:03:17