通过使用XJC,我用每个包中的ObjectFactory类创建了2个不同的JAXB元数据包(我不知道这种方法是否可行,我有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");

最佳答案

从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
}

还有这个:
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);
    }
}

关于java - 多个JAXBContext实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13399567/

10-09 12:57