Multiple JAXBContext instances
java, jaxb, marshalling
Solution
From the Javadoc for JAXBContext:
A client application normally obtains new instances of this class using one of these
two styles for newInstance methods, although there are other specialized forms of the
method available:
JAXBContext.newInstance( "com.acme.foo:com.acme.bar" )
The JAXBContext instance is initialized from a list of colon separated Java package
names. Each java package contains JAXB mapped classes, schema-derived classes and/or
user annotated classes. Additionally, the java package may contain JAXB package annotations
that must be processed. (see JLS 3rd Edition, Section 7.4.1. Package Annotations).
JAXBContext.newInstance( com.acme.foo.Foo.class )
The JAXBContext instance is intialized with class(es) passed as parameter(s) and
classes that are statically reachable from these class(es). See newInstance(Class...)
for details.
You can use a shared context and initialize it with a list of package names.
Code Example:
package test.jaxb.one;
@XMLRootElement
@XMLType(name = "test.jaxb.one.SimpleObject")
@XMLAccessorType(XMLAccessType.FIELD)
public class SimpleObject implements Serializable {
private static final long serialVersionUID = 54536613717262557148L;
@XmlElement(name = "Name")
private String name;
// Constructor, Setters/Getters
}
and this one:
package test.jaxb.two;
@XMLRootElement
@XMLType(name = "test.jaxb.two.SimpleObject")
@XMLAccessorType(XMLAccessType.FIELD)
public class SimpleObject implements Serializable {
private static final long serialVersionUID = -4073071224211934153L;
@XmlElement(name = "Name")
private String name;
// Constructor, Setters/Getters
}
Finally:
public class JAXBTest {
@Test
public void testContextLoad() throws Exception {
final JAXBContext context = JAXBContext
.newInstance("test.jaxb.one:test.jaxb.two");
Assert.assertNotNull(context);
}
}
Problem
By using XJC, I create 2 different JAXB metadata packages with an ObjectFactory class in each package (I dont know if this approach is OK, I have 2 different XSD's to work on ) It is recommended to create only one JAXBContext per operation, because it is costy. So I wonder if what I'm doing here is valid and good practise? ``` JAXBContext jaxbContext = JAXBContext.newInstance("com.package.one"); Unmarshaller jaxbUnmarshaller1 = jaxbContext.createUnmarshaller(); JAXBContext jaxbContext2 = JAXBContext.newInstance("com.package.two"); Unmarshaller jaxbUnmarshaller2 = jaxbContext2.createUnmarshaller(); ``` EDIT when i try to initialize 2 packages together i get an exception "The element name {}Value has more than one mapping." Value is a class in both packages. ``` JAXBContext jaxbContext = JAXBContext.newInstance("com.package.one:com.package.two"); ```