22/08/2019

[Maven] Generate Avro sources at compile time

If you are using Apache Avro in your project, you might want to automatize the sources generation step so that at every compile, the target classes are built from the Avro schema.

In Maven, this can be done with the avro-maven-plugin with a configuration as such:

 <project>  
   <modelVersion>4.0.0</modelVersion>  
   <groupId>com.blogspot.groglogs</groupId>  
   <artifactId>sample-avro-maven-pom</artifactId>  
   <version>1</version>  
   
   <dependencies>  
     <dependency>  
       <groupId>org.apache.avro</groupId>  
       <artifactId>avro</artifactId>  
     </dependency>  
   
     <!--   
     Use this for testing purposes only if you wish to manually generate the classes from Avro sources:  
   
     java -jar avro-tools.jar compile schema SCHEMA_FILE.avsc TARGET_DIRECTORY  
   
     See: https://avro.apache.org/docs/current/gettingstartedjava.html  
     <dependency>  
       <groupId>org.apache.avro</groupId>  
       <artifactId>avro-tools</artifactId>  
       <scope>provided</scope>  
     </dependency>  
     -->  
   </dependencies>  
   
   <build>  
     <plugins>  
       <plugin>  
         <groupId>org.apache.avro</groupId>  
         <artifactId>avro-maven-plugin</artifactId>  
         <executions>  
           <execution>  
             <phase>generate-sources</phase>  
             <goals>  
               <goal>schema</goal>  
             </goals>  
             <configuration>  
               <sourceDirectory>SOURCE_DIR</sourceDirectory>  
               <outputDirectory>DEST_DIR</outputDirectory>  
             </configuration>  
           </execution>  
         </executions>  
       </plugin>  
     </plugins>  
   </build>  
 </project>  


Remember that it is also possible to use avro-tools to manually generate sources from a schema.

No comments:

Post a Comment

With great power comes great responsibility