gpt4 book ai didi

java - 多个 JAXBContext 实例

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:09 26 4
gpt4 key购买 nike

通过使用 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 个包时,出现异常“元素名称 {}Value 有多个映射。”值是两个包中的一个类。

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

最佳答案

来自 JAXBContext 的 Javadoc:

A client application normally obtains new instances of this class using one of thesetwo styles for newInstance methods, although there are other specialized forms of themethod available:JAXBContext.newInstance( "com.acme.foo:com.acme.bar" )The JAXBContext instance is initialized from a list of colon separated Java packagenames. Each java package contains JAXB mapped classes, schema-derived classes and/oruser annotated classes. Additionally, the java package may contain JAXB package annotationsthat 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) andclasses 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com