Xml Binding via JaxB is a standard way to work with Xml objects in Java 6 and beyond. While there are ant tools and cmd line utilities to automate this, externalizing the automation in a dedicated maven module, along with nice wrapper methods for a fluent api would be nice. Below are the steps to generate jaxb objects with a fluent api via Maven Pom configuration.
Source Structure
- src/main/resources/sample.xsd
- src/main/resources/binding/binding.xjb
<bindings xmlns="http://java.sun.com/xml/ns/jaxb" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<globalBindings>
<javaType name="java.util.Calendar" xmlType="xs:date"
parseMethod="javax.xml.bind.DatatypeConverter.parseDate"
printMethod="javax.xml.bind.DatatypeConverter.printDate"
/>
</globalBindings>
</bindings>
- Finally, integrate jaxb compile and generate step via pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>common-xml-schema</artifactId>
<packaging>jar</packaging>
<name>Common Schema and JaxB Module</name>
<description>Common Module to hold all XML Schemas and JaxB objects</description>
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- It's advised not to checkin the generated classes. By default they are generated in target/generated-sources with xmlns namespace provided
in xsd. If you need the sources to be generated uncomment the below.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<packagename>xxx.schema</packagename>
<schemaDirectory>${basedir}/src/main/resources</schemaDirectory>
<outputdirectory>${basedir}/src/main/java/xxx/generated</outputdirectory>
</configuration>
</plugin>
-->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<configuration>
<extension>true</extension>
<args>
<arg>-Xfluent-api</arg>
</args>
<plugins>
<plugin>
<groupId>net.java.dev.jaxb2-commons</groupId>
<artifactId>jaxb-fluent-api</artifactId>
<version>2.1.8</version>
</plugin>
</plugins>
<bindingDirectory>src/main/resources/binding</bindingDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Post a Comment