Avner Levy
Avner Levy

Reputation: 6741

Generating automatically the jaxb.index file using maven

I have a package with multiple java classes inside.
I need to read xml files with the package's classes data.
Is there an automatic way (using maven) to generate the ObjectFactory class or the jaxb.index file from the content of the package?
I'm aware I can initiate the jaxb context with specific classes but this will force me to change the code each time I add a new class.
Thanks in advance,
Avner

Upvotes: 2

Views: 3488

Answers (3)

Pawel Veselov
Pawel Veselov

Reputation: 4225

The "easiest" way to do this is using Atteo's class index. Having this Maven dependency:

<dependency>
    <groupId>org.atteo.classindex</groupId>
    <artifactId>classindex</artifactId>
    <version>3.13</version>
</dependency>

will add an annotation processor to the build.

Adding @IndexSubclasses annotation to the corresponding package-info.java will make that annotation processor generate jaxb.index file. I.e.:

@XmlSchema(
        namespace = "https://schemas.com/super.xsd",
        elementFormDefault = XmlNsForm.QUALIFIED
)
@XmlAccessorType(XmlAccessType.FIELD)
@IndexSubclasses
package pkg.with.my.schema;

import org.atteo.classindex.IndexSubclasses;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

IMPORTANT A big drawback for this approach is that Atteo's annotations have RUNTIME retention; therefore, the dependency must be included as a runtime dependency as well as a compile-time one. If you are building a self-contained jar, that would no longer possible with using Atteo's class index, unless you shade or build jar with dependencies.

Upvotes: 0

Avner Levy
Avner Levy

Reputation: 6741

After doing some research I've chosen to use the API JAXBContext.newInstance which accepts an array of classes. I've written a short wrapper which accepts packages names and scan them using spring for the relevant classes (based on the XmlRootElement annotation). then I use the above API for creating the jaxb context. Since it is an expensive operation you should consider to cache these contexts (which are thread safe) for future use.

Upvotes: 0

khmarbaise
khmarbaise

Reputation: 97359

You have to use the jaxb2-maven plugin to generate other things. If the classes have the appropriate annotations it shouldn't be a problem.

<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.3.1</version>

See here: http://mojo.codehaus.org/jaxb2-maven-plugin/

Upvotes: 1

Related Questions