Generate Plain Old Java Objects (POJOs) from XML Schema Definitions with Maven

My blog post Generate Plain Old Java Objects (POJOs) from XML Schema Definitions with xjc is pretty popular, and I've enjoyed getting use out of it myself. But the problem with this is that it introduces a number of source files into your repo, which you then need to maintain in terms of your own code style standards, maybe manage Javadoc, and generally add a lot of code to your codebase that isn't yours.

One thing we can do instead is utilise the Mojohaus jaxb2-maven-plugin's xjc goal to automagically generate these files each time we do a build.

To make this work, we need to do two things. Firstly, we need to put the XML Schema Definition (XSD) in our project under the src/main/xsd directory. The plugin will iterate over all XSDs it can find, generating them as necessary.

Next we need to add the Maven configuration to hook in the plugin:

  <!-- ... -->
  <build>
    <plugins>
      <!-- ... -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <version>2.5.0</version>
        <executions>
          <execution>
            <id>xjc</id>
            <goals>
              <goal>xjc</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

It's that simple! You can now reference the classes from your regular code, but you may need to compile the project first if the classes aren't showing up in your IDE.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #maven #java #xml.

This post was filed under articles.

Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.