Generate Java Classes From XSD

This example shows you how to generate Java Classes from XSD using jaxb2-maven-plugin. This plugin uses the XJC which is a JAXB Binding compiler tool that can generate Java Classes from XSD.

Maven Project Dependencies

We use the jaxb2-maven-plugin maven plugin to transform our XSD schema into Java Classes. These Java Classes will be generated in the target/generated-resources/jaxb folder by default. You could override the output directory by adding a child element outputDirectory to the configuration element. If you use this custom output directory your files will be cleared/replaced on every build. If you add extra classes to these directories you must also add the clearOutputDir with a value of false.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""

    <name>XSD - ${project.artifactId}</name>




Global JAX-B bindings

We can provide a global bindings file. These binding declarations override the default binding rules. Like in this example we override the dateTime type to the java.util.Calendar type.

<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings version="2.1"

        <jaxb:serializable uid="1"/>

        <!-- date time adapter -->
        <jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
                       printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />



Generate Java Classes from XSD

This XSD schema will be used to generate the Java Classes. It is important to always change your XSD file and let the classes be generated. Don’t modify the generated Java Classes because these are re-generated on every build.

<xs:schema xmlns:xs=""

    <xs:complexType name="CourseRequest">
            <xs:element name="id" type="xs:int" nillable="false"/>

    <xs:complexType name="CourseResponse">
            <xs:element name="id" type="xs:int"/>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="description" type="xs:string"/>
            <xs:element name="created" type="xs:dateTime"/>


Running the example

When we run this example with maven, the java classes are created from the xsd schema using the jaxb2-maven-plugin.

mvn clean package





You may also like...