-->

Set MOXy as JAXB Provider without properties file

2020-07-24 06:33发布

问题:

I am trying to use MOXy as my JAXB provider in order to marshal/unmarshal content into XML/JSON.

I have created the "jaxb.properties" file with as content : javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactor

Everything works fine.

        JAXBContext jaxbContext = JAXBContext.newInstance(ServerInformation.class); // The jaxb.properties must be in the same package as "ServerInformation.java"
        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);

My question is: is there any solution to put this file in another package ? I am using a Maven plugin "wadl2java" to generate some packages and class, and after every Maven build, all packages are deleted and re-created. So I loose this file every time... I would like a solution to set MOXy as my JAXB provider without the "jaxb.properties" in my ressource package. I have some others packages in the same project, and I can put this file in.

Any idea ?

Thanks you.

回答1:

There are several ways how to set MOXy as JAXB Provider.

  1. To set system property JAXBContext.JAXB_CONTEXT_FACTORY to org.eclipse.persistence.jaxb.JAXBContextFactory

    • http://docs.oracle.com/javaee/7/api/javax/xml/bind/JAXBContext.html#JAXB_CONTEXT_FACTORY
  2. To create META-INF/services/javax.xml.bind.JAXBContext file with org.eclipse.persistence.jaxb.JAXBContextFactory

    • http://docs.oracle.com/cd/E24329_01/web.1211/e24964/data_types.htm#WSGET346
  3. using org.eclipse.persistence.jaxb.JAXBContextFactory

    • Can I replace jaxb.properties with code?