我们正在使用JAXB构建许多开发人员应用程序,并且仍然遇到问题,这些问题都会回到JAXB对象的生产者和使用者之间的"版本"不匹配.
进程并没有减轻痛苦,因此我正在考虑JAXB的CORBA对象版本控制的内容,可能是通过必须匹配的必需最终字段.作为额外的奖励,我想将版本值注入Maven版本#:-)
这都是使用注释,没有xsd.
思考?
谢谢.
-----澄清-----
可以将其视为Serializable serialVersionUID,当对象被封送并且是必需的时,它将被添加到编组流中,并且当对象被解组时将检查其值.
可以实现各种检查规则,但在这种情况下,我只想要相等.如果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;
}
}
Run Code Online (Sandbox Code Playgroud)
演示
在您的演示代码中,利用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);
}
}
Run Code Online (Sandbox Code Playgroud)
有效使用案例
input.xml中/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="123">
<bar>ABC</bar>
</foo>
Run Code Online (Sandbox Code Playgroud)
无效使用案例
input.xml中
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo VERSION="1234">
<bar>ABC</bar>
</foo>
Run Code Online (Sandbox Code Playgroud)
产量
Exception in thread "main" java.lang.RuntimeException: VERSION MISMATCH
at forum12218164.Demo.main(Demo.java:23)
Run Code Online (Sandbox Code Playgroud)