有几个项目可能会给您带来问题。
基础实体
默认情况下,JAX-RS 实现会创建一个JAXBContext
在本例中,关于服务方法的返回类型或参数Represenatation
。在处理域模型时,JAXB impl 还将引入引用的类型,例如BaseEntity
。它不能自动拉入子类,所以我们可以使用@XmlSeeAlso
注释来引用那些。
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlDiscriminatorNode;
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlDiscriminatorNode("@type")
@XmlSeeAlso({AbcEntity.class, XyzEntity.class})
public abstract class BaseEntity {
private String firstName;
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
jaxb.属性
也因为@XmlDescriminatorNode
/@XmlDescriminatorValue
您需要确保指定 MOXy 作为您的 JAXB 提供者的 MOXy 扩展。这是通过添加一个名为的文件来完成的jaxb.properties
在与您的域模型相同的包中,包含以下条目。
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
下面是一个模仿 RESTful 服务功能的独立示例。
import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlRootElement;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Representation.class);
Representation rep = new Representation();
BaseEntity entity = new XyzEntity();
entity.setFirstName("first-name");
entity.setLastName("last-name");
rep.setEntity(entity);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rep, System.out);
}
@XmlRootElement
static class Representation {
private BaseEntity entity;
public BaseEntity getEntity() {
return entity;
}
public void setEntity(BaseEntity entity) {
this.entity = entity;
}
}
}
Output
以下是运行演示代码的输出。看到type
属性现已存在。
<?xml version="1.0" encoding="UTF-8"?>
<representation>
<entity type="xyz">
<firstName>first-name</firstName>
<lastName>last-name</lastName>
</entity>
</representation>
了解更多信息
- 指定 EclipseLink MOXy 作为您的 JAXB 提供程序 http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
- JAXB 和继承 - MOXy 扩展 @XmlDecriminatorNode/@XmlDecrimintatorValue http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-moxy-extension.html
- 更新 WebLogic 中的 EclipseLink http://blog.bdoughan.com/2012/10/updating-eclipselink-in-weblogic.html