我们正在使用 JAXB 构建许多开发人员应用程序,并不断遇到问题,这些问题都归结为 JAXB 对象的生产者和消费者之间的“版本”不匹配。
过程并没有减轻痛苦,所以我正在考虑一些类似于 JAXB 的 CORBA 对象版本控制的方法,可能是通过值必须匹配的必需的最终字段。作为额外的奖励,我想将版本值注入(inject)为 Maven 版本 # :-)
这都是使用注释,没有xsd。
想法?
谢谢。
----- 澄清 -----
将此视为一个可序列化的 serialVersionUID,当对象被编码(marshal)并且是必需的时,它被添加到编码(marshal)流中,并且在对象被取消编码(marshal)时检查其值。
可以实现各种检查规则,但在这种情况下,我只想要相等。如果 Foo 的当前版本是 1.1,并且您将数据发送给 unmarshal,其版本不是 1.1,我将拒绝它。
帮助?
最佳答案
您可以执行以下操作:
富
将版本字段添加到您的根模型对象。
package forum12218164;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Foo {
@XmlAttribute
public static final String VERSION = "123";
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
演示
在您的演示代码中,在确定执行解码操作是否安全之前,利用 StAX 解析器检查版本属性:
package forum12218164;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
// Create the JAXBContext
JAXBContext jc = JAXBContext.newInstance(Foo.class);
// Create an XMLStreamReader on XML input
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("src/forum12218164/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
// Check the version attribute
xsr.nextTag(); // Advance to root element
String version = xsr.getAttributeValue("", "VERSION");
if(!version.equals(Foo.VERSION)) {
// Do something if the version is incompatible
throw new RuntimeException("VERSION MISMATCH");
}
// Unmarshal for StAX XMLStreamReader
Unmarshaller unmarshaller = jc.createUnmarshaller();
Foo foo = (Foo) unmarshaller.unmarshal(xsr);
// Marshal the Object
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
有效用例
输入.xml/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="123">
<bar>ABC</bar>
</foo>
无效用例
输入.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="1234">
<bar>ABC</bar>
</foo>
输出
Exception in thread "main" java.lang.RuntimeException: VERSION MISMATCH
at forum12218164.Demo.main(Demo.java:23)
关于jaxb - "Versioning"JAXB 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218164/