[Java] Make XJC maven tasks generate serializable JAXB classes

While using ehcache to cache RESTful calls to webservices, i dealt with the problem, that ehcache was sometimes not able to cache generated my xjc generated java classes from xsd, because in default they are not implementing the serializable Interface.

To fix this i found a simple solution by adding the bindung element and usind a global binding.

<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
          xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
          xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
          xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
          version="2.1">
    <globalBindings>
        <serializable uid="1" />
    </globalBindings>
</bindings>

and adding:

<binding dir="${basedir}/src/main/resources/service-api">
    <include name="bindings.xml"/>
</binding>

So the resulting maven task looks like this:

<tasks>
    <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
        <classpath refid="maven.compile.classpath"/>
    </taskdef>
    <property name="gensrc.target" value="${basedir}/gensrc/main/java"/>
    <mkdir dir="${gensrc.target}"/>
    <xjc package="com.mypackage" destdir="${gensrc.target}" readonly="false" header="false"
         extension="true" removeOldOutput="false">
        <schema dir="${basedir}/src/main/resources/service-api">
            <include name="SASResponse.xsd"/>
        </schema>
        <binding dir="${basedir}/src/main/resources/service-api">
            <include name="bindings.xml"/>
        </binding>
        <depends dir="${gensrc.target}">
            <include name="**/*"/>
        </depends>
        <produces dir="${gensrc.target}">
            <include name="**/*.java"/>
        </produces>
    </xjc>
</tasks>

Now the generated classes implement the Serializable interface and can be used in ehCache.

November 6, 2015
||||||

Related Posts

Leave a reply