我使用EclipseLink外部映射文件將Java對象編組爲XML和JSON。由於我的模型類是在不同的項目中定義的,我不能添加/修改任何文件或類。EclipseLink MOXy - 如何避免保留模型類包中的jaxb.index和jaxb.properties文件?
那麼我怎樣才能避免保留我的模型類所在的包中的jaxb.index和jaxb.properties文件?
我使用EclipseLink外部映射文件將Java對象編組爲XML和JSON。由於我的模型類是在不同的項目中定義的,我不能添加/修改任何文件或類。EclipseLink MOXy - 如何避免保留模型類包中的jaxb.index和jaxb.properties文件?
那麼我怎樣才能避免保留我的模型類所在的包中的jaxb.index和jaxb.properties文件?
Java模型
Belos是Java模型,我將使用這個例子:
富
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>
DEMO
下面演示代碼演示瞭如何指定外部映射文件。
消除jaxb.properties
爲了消除jaxb.properties
文件(這是指定JAXB提供標準的機制,請參閱:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html),我們將使用原生API的莫西來引導的JAXBContext
。
消除jaxb.index
在這個例子中oxm.xml
文件播放爲jaxb.index
同樣的作用。由於我們需要傳遞一些信息來創建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>
感謝您的回覆Blaise。我們能否使用類路徑中存在的jaxb.properties提供eclipselink jaxbprovider,是否有必要將此文件保存在與模型類相同的包中?我可以在你的示例中看到jaxb.properties存在於foo包中,但Bar使用的是默認的jaxbContext,但在我的情況下,所有模型類都存在於其他包中(我沒有任何控制權),而且我不想要爲這些模型類創建任何包裝類,並將jaxb.properties保留在該包裝類包中。 – Navin 2012-07-24 19:07:04
@Navin - 使用默認機制,您只需要一個'jaxb.properties'文件。它可以在任何你正在創建'JAXBContext'的包中。它不需要全部都是。 – 2012-07-24 19:13:45