Specifying the MOXy runtime for multiple Java packages

人盡茶涼 提交于 2020-01-04 04:37:27

问题


Is there a way to specify MOXy as my JAXB implementation, for domain classes spread across multiple Java packages, other than putting jaxb.properties into every single package?


回答1:


To specify EclipseLink MOXy as the JAXB provider you need to put a jaxb.properties in one of the packages for your domain objects, that is passed in to bootstrap the JAXBContext. For example if your JAXBContext will be based on the following 2 classes:

  • example.foo.Foo
  • example.bar.Bar

example.foo.Foo

package example.foo;

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

import example.bar.Bar;

@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    private Bar bar;

}

example.bar.Bar

package example.bar;

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

import example.foo.Foo;

@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {

    private Foo foo;

}

example/foo/jaxb.properties

To specify that the MOXy implementation of JAXB should be used we will put a jaxb.properties file with the following entry in the same package as the Foo class.

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

Demo

Since the Foo and Bar classes reference each other, ultimately the JAXBContext will contain metadata about both of them, but based on how we create the JAXBContext the provider can be different.

package example;

import javax.xml.bind.JAXBContext;
import example.foo.Foo;
import example.bar.Bar;

public class Demo {

    public static void main(String[] args) throws Exception{
        System.out.println(JAXBContext.newInstance(Foo.class).getClass());
        System.out.println(JAXBContext.newInstance(Bar.class).getClass());
        System.out.println(JAXBContext.newInstance(Foo.class, Bar.class).getClass());
    }

}

Running the above code will produce:

class org.eclipse.persistence.jaxb.JAXBContext
class com.sun.xml.bind.v2.runtime.JAXBContextImpl
class org.eclipse.persistence.jaxb.JAXBContext


来源:https://stackoverflow.com/questions/5862896/specifying-the-moxy-runtime-for-multiple-java-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!