Wednesday, 8 October 2014

Generating toString() method in JAX-B generated classes

First of all, this post is inspired by this blog post by Dustin Marx.

What is described below is what you should do with Maven to achieve similar goals in contrast with original post where Ant is used.

So, in your pom.xml of module where generated classes will reside, simply
within <build>/<plugins> section include the following snippet:


<plugin>
     <groupId>org.codehaus.mojo</groupId>
     <artifactId>jaxb2-maven-plugin</artifactId>
     <dependencies>
           <dependency>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-basics</artifactId>
                <version>0.9.0</version>
           </dependency>
      </dependencies>
            <executions>
                    <execution>
                        <id>xjc2</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                        <configuration>
                            <arguments>-XtoString</arguments>
                            <extension>true</extension>
                            <packageName>your.desired.package</packageName>                             <schemaDirectory>/location/of/schema.xsd</schemaDirectory>
                    </configuration>
             </execution>
     </executions>

</plugin>

Now, your further build will fail (unless you are already ahead and have foreseen what is required in addition to given above) saying:
package org.jvnet.jaxb2_commons.lang does not exist

Not too surprising as generated code is again dependent on jaxb2-basics artifact as generated
toString method is referencing it, e.g:

public String toString() {
    final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
    final StringBuilder buffer = new StringBuilder();
    append(null, buffer, strategy);
    return buffer.toString();

}

You will need same dependency as your's module dependency for everything to work as expected.
So under <project>/<dependencies> add:


<dependency>

       <groupId>org.jvnet.jaxb2_commons</groupId>
       <artifactId>jaxb2-basics</artifactId>
       <version>0.9.0</version>
</dependency>

Of course, you can opt for factoring this out into dependency and plugin management sections of your parent module, but that is another story :)