2012-04-13 51 views
1

所以給我上課名稱:MOXy能否將POJO與getter序列化,而不需要在每個getter中顯式地註釋註釋?

class Name { 
    private String first; 
    private String middle; 
    private String last; 

    public getFirst() { return first; } 
    public getMiddle() { return middle; } 
    public getLast() { return last; } 
} 

我想序列化使用XML映射這個類的實例,而無須列出在XML映射每個屬性:

<java-types> 
    <java-type name="Name"> 
     <java-attributes> 
      <xml-element java-attribute="first"/> 
      <xml-element java-attribute="middle"/> 
      <xml-element java-attribute="last"/> 
     </java-attributes> 
    </java-type> 
</java-types> 

所以最好我想有映射文件是這樣的:

<java-types> 
    <java-type name="Name" xml-accessor-type="GETTERS"/> 
</java-types> 

我有一些遺留的DTO類這樣的打算只用於序列(N o setter)有30個或更多的屬性,理想情況下我想避免在映射文件中列出每個屬性。

回答

0

注:我是EclipseLink JAXB (MOXy)鉛和JAXB 2 (JSR-222)專家小組的成員。

對於這種用例,我建議使用字段訪問類型。當指定這個時,JAXB實現將使用字段(實例變量)來訪問數據而不是通過屬性(get方法)。下面我將演示如何做到這一點使用莫西的外部映射文件的擴展名:

bindings.xml

<?xml version="1.0"?> 
<xml-bindings 
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm" 
    package-name="forum10141543"> 
    <java-types> 
     <java-type name="Name" xml-accessor-type="FIELD"> 
      <xml-root-element/> 
     </java-type> 
    </java-types> 
</xml-bindings> 

名稱

package forum10141543; 

class Name { 
    private String first; 
    private String middle; 
    private String last; 

    public Name() { 
    } 

    public Name(String first, String middle, String last) { 
     this.first = first; 
     this.middle = middle; 
     this.last = last; 
    } 

    public String getFirst() { return first; } 
    public String getMiddle() { return middle; } 
    public String getLast() { return last; } 
} 

jaxb.properties

指定MOXy作爲您的JAXB prov ider你需要添加一個名爲jaxb.properties的文件與你的域類具有以下條目在同一個包中。

javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory 

演示

下面的代碼演示瞭如何在綁定傳遞自舉時文件中JAXBContext

package forum10141543; 

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

public class Demo { 

    public static void main(String[] args) throws Exception { 
     Map<String, Object> properties = new HashMap<String, Object>(1); 
     properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum10141543/bindings.xml"); 
     JAXBContext jc = JAXBContext.newInstance(new Class[] {Name.class}, properties); 

     Name name = new Name("Jane", "Anne", "Doe"); 
     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.marshal(name, System.out); 
    } 

} 

輸出

<?xml version="1.0" encoding="UTF-8"?> 
<name> 
    <first>Jane</first> 
    <middle>Anne</middle> 
    <last>Doe</last> 
</name> 

更多信息