问题
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