jaxb - EclipseLink MOXy - 如何避免将 jaxb.in​​dex 和 jaxb.properties 文件保留在模型类包中?

标签 jaxb eclipselink moxy

我正在使用 EclipseLink 外部映射文件将 Java 对象编码为 XML 和 JSON。由于我的模型类是在不同的项目中定义的,我无权添加/修改任何文件或类。

那么如何避免将 jaxb.in​​dex 和 jaxb.properties 文件保留在我的模型类所在的包中?

最佳答案

JAVA模型

Belos 是我将用于此示例的 Java 模型:

Foo

package forum11615376;

public class Foo {

    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void setBar(Bar bar) {
        this.bar = bar;
    }

}

酒吧

package forum11615376;

public class Bar {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

外部映射文件 (oxm.xml)

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum11615376">
    <java-types>
        <java-type name="Foo">
            <xml-root-element name="FOO"/>
            <java-attributes>
                <xml-element java-attribute="bar" name="BAR"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

演示

下面的演示代码演示了如何指定外部映射文件。

消除 jaxb.properties

为了消除 jaxb.properties 文件(这是指定 JAXB 提供程序的标准机制,请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html),我们将使用 native MOXy API 来引导 JAXBContext .

消除 jaxb.in​​dex

在此示例中,oxm.xml 文件与 jaxb.in​​dex 发挥相同的作用。由于我们需要传递一些内容来创建 JAXBContext,因此我们将使用一个空的 Class[]

package forum11615376;

import java.util.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum11615376/oxm.xml");
        JAXBContext jc = JAXBContextFactory.createContext(new Class[] {}, properties);

        Bar bar = new Bar();
        bar.setValue("Hello World");
        Foo foo = new Foo();
        foo.setBar(bar);

        Marshaller marshaller =jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

输出

下面是运行演示代码的输出。如您所见,映射元数据已应用。

<?xml version="1.0" encoding="UTF-8"?>
<FOO>
   <BAR>
      <value>Hello World</value>
   </BAR>
</FOO>

关于jaxb - EclipseLink MOXy - 如何避免将 jaxb.in​​dex 和 jaxb.properties 文件保留在模型类包中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11615376/

相关文章:

java - JPA NamedQuery 不在 Glassfish4 中(但在 Glassfish3 中有效)

java - CriteriaBuilder JPA 2.0 Eclipse链接

java - 支持 MOXy @XmlPath 表达式吗?

java - 线程 "main"javax.xml.bind.PropertyException : name: eclipselink. 媒体类型值中的异常:application/json

java - 如何向 org.apache.wink 生成的 ATOM feed 添加处理指令

jpa - 如何将javax.validation导入我的Java SE项目?

Java 类到 XSD

java - 解码数组不会给我任何值

java - JAXB 编码期间的类转换

java - 使用 IDResolver 时解码 JAXB 集合失败,因为 IDResolver 对象作为目标类型