我们正在使用JAXB构建许多开发人员应用程序,并且仍然遇到问题,这些问题都会回到JAXB对象的生产者和使用者之间的“版本”不匹配。
进程并没有减轻痛苦,因此我正在考虑JAXB的CORBA对象版本控制的内容,可能是通过必须匹配的必需最终字段。作为额外的奖励,我想将版本值注入Maven版本#: - )
这都是使用注释,没有xsd。
思想?
感谢。
-----澄清-----
将此视为Serializable serialVersionUID,当对象被封送并且是必需的并且当对象被解组时其值已检查时,该序列可添加到编组流中。
可以实现各种检查规则,但在这种情况下,我只想要相等。如果Foo的当前版本是1.1并且您将数据发送给unmarshal,其版本不是1.1,我会拒绝它。
帮助?
答案 0 :(得分:6)
您可以执行以下操作:
<强>富强>
向根模型对象添加版本字段。
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);
}
}
有效使用案例
的 input.xml中/输出强> 的
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="123">
<bar>ABC</bar>
</foo>
无效使用案例
的 input.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)