javamavenavroavsc

Add annotations in classes generated by avro-maven-plugin


I am generating Java classes from an AVSC file using the avro-maven-plugin and I want to add a @JsonProperty annotation on some of the class fields.

I want to understand how I can do that. The record.vm file in the configuration does mention of a tag javaAnnotation but it does not work as expected.

pom.xml

<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>${avro.version}</version>
<dependencies>
    ...
</dependencies>
<executions>
    <execution>
        <phase>generate-sources</phase>
        <goals>
            <goal>schema</goal>
        </goals>
        <configuration>
            <fieldVisibility>PRIVATE</fieldVisibility>
            <enableDecimalLogicalType>true</enableDecimalLogicalType>
            <stringType>String</stringType>
            <templateDirectory>/com/.../avro/compiler/specific/templates/</templateDirectory>
            <dateTimeLogicalTypeImplementation>joda</dateTimeLogicalTypeImplementation>
        </configuration>
    </execution>
</executions>

Snipit from record.vm enter image description here

I want the generated class to look like this

enter image description here

I tried something like this but it did not work

[{
    "namespace": "com..avro",
    "type": "record",
    "name": "myClass",
    "fields": [
        {
            "name": "my_variable", 
            "type": "int",
            "javaAnnotations":"com.fasterxml.jackson.annotation.JsonProperty(\"my_variable\")",
            "javaAnnotations":[
                "com.fasterxml.jackson.annotation.JsonProperty(\"my_variable\")"
            ]
        }
    ]
}]

Solution

  • You can specify both class-level annotations and field-level annotations by adding a "javaAnnotation" field at the appropriate point in the avsc definition:

    [{
        "namespace": "com..avro",
        "type": "record",
        "name": "myClass",
        "javaAnnotation": "MyClassAnnotation",
        "fields": [
            {
                "name": "my_variable", 
                "type": "int",
                "javaAnnotation": "com.fasterxml.jackson.annotation.JsonProperty(\"my_variable\")"
            }
        ]
    }]