多个JAXBContext实例

时间:2012-11-15 14:28:30

标签: java jaxb marshalling

通过使用XJC,我在每个包中创建了2个不同的JAXB元数据包和一个ObjectFactory类(我不知道这种方法是否正常,我有2个不同的XSD可以使用)

建议每次操作只创建一个JAXBContext,因为它很省钱。所以我想知道我在这里做的事情是否有效和良好的做法?

    JAXBContext jaxbContext = JAXBContext.newInstance("com.package.one");
    Unmarshaller jaxbUnmarshaller1 = jaxbContext.createUnmarshaller();

    JAXBContext jaxbContext2 = JAXBContext.newInstance("com.package.two");
    Unmarshaller jaxbUnmarshaller2 = jaxbContext2.createUnmarshaller();

编辑当我尝试初始化2个包时,我得到一个异常“元素名称{}值有多个映射。”值是两个包中的一个类。

 JAXBContext jaxbContext = JAXBContext.newInstance("com.package.one:com.package.two");

1 个答案:

答案 0 :(得分:17)

来自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.

您可以使用共享上下文并使用包名列表对其进行初始化。

代码示例:

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
}

和这一个:

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
}

最后:

public class JAXBTest {
    @Test
    public void testContextLoad() throws Exception {
        final JAXBContext context = JAXBContext
            .newInstance("test.jaxb.one:test.jaxb.two");
        Assert.assertNotNull(context);
    }
}