我们遇到的问题是必须为同一个 JAVA 对象生成不同的 XML 表示。
例如我们有一个用户类,其中包含 secret 信息,例如上次登录日期或生日。
为了归档,我们需要一个带有lastLoginDate的完整的XML表示 和生日。
但是,对于与外部合作伙伴的数据交换,我们不希望 包含此 secret 信息。
因此,对象始终是相同的,但是我们希望将其编码(marshal)到一个上下文中的一个 XML 表示形式,并在另一个上下文中将其编码(marshal)到另一个 XML 表示形式中。
@XmlType
public class UserData implements UserInfoBean {
private String firstName;
private String lastName;
private Timestamp lastLogin;
@XmlAttribute(required = false)
public Timestamp getLastLogin() {
return lastLogin;
}
public void setLastLogin(Timestamp lastLogin) {
this.lastLogin = lastLogin;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstname) {
this.firstName = truncate(firstname, 50);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastname) {
this.lastName = truncate(lastname, 80);
}
...
}
目前我们使用java-annotation来详细配置XML。但是我们还没有找到任何方法来提供两种不同的 jaxb 配置。
谢谢
华伦斯坦
最佳答案
有多种方法可以解决这个问题。
最简单的可能是使用 MOXy XML Bindings 。您可以拥有多个绑定(bind)并使用其中一个版本创建 JAXBContext
:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream iStream = classLoader.getResourceAsStream("metadata/normal-xml-bindings.xml");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
JAXBContext ctx = JAXBContext.newInstance(new Class[] { Customer.class }, properties);
或者,您也可以编写自定义注释读取器并在创建 JAXBContext
时使用它。例如,如果存在某个附加注释,此自定义注释读取器可以抑制某些属性。
public class CustomAnnotationReader extends
AbstractInlineAnnotationReaderImpl<Type, Class, Field, Method>
implements RuntimeAnnotationReader { ... }
// ....
final RuntimeAnnotationReader annotationReader = new CustomAnnotationReader();
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBRIContext.ANNOTATION_READER, annotationReader);
final JAXBContext context = JAXBContext.newInstance(
contextPath, Thread.currentThread()
.getContextClassLoader(), properties);
我个人可能会使用自定义注释阅读器 - 这将允许保留注释(而不是 XML 绑定(bind))。
关于java - JAX-B 的多种配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350406/