Jaxb:为固定值属性生成常量值

Sco*_*pio 5 java xsd wsdl2java jaxb

我正在使用xsd,它使用以下结构:

<xs:attribute name="listVersionID" type="xs:normalizedString" use="required" fixed="1.0">
Run Code Online (Sandbox Code Playgroud)

虽然本身没有问题,但使用起来相当烦人,因为这个定义的固定值在xsd规范的发布之间增加,我们需要修改单独的常量类中的值以保持它们有效,尽管很少如果xsd感兴趣的内容发生了变化.xsd在其他地方维护,所以只是改变它是没有选择的.

因此我问自己是否有一个jaxb-plugin或类似的将固定值属性转换为常量ala

@XmlAttribute(name = "listVersionID")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
@XmlSchemaType(name = "normalizedString")
protected final String listVersionID = "1.0";
Run Code Online (Sandbox Code Playgroud)

而不仅仅是

@XmlAttribute(name = "listVersionID")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
@XmlSchemaType(name = "normalizedString")
protected String listVersionID;
Run Code Online (Sandbox Code Playgroud)

必须手动填充.

有谁知道这样的?

jma*_*eis 4

是的,可以通过自定义 jaxb 绑定来实现,该绑定可以作为文件添加到代码生成器中。

在 jaxb 绑定中,有fixedAttributeAsConstantProperty- 属性。将其设置为 true,指示代码生成器生成属性,并将该fixed属性作为 java 常量。

有 2 个选项:

1.通过全局绑定:然后将所有具有固定值的属性设置为常量

<schema targetNamespace="http://stackoverflow.com/example" 
        xmlns="http://www.w3.org/2001/XMLSchema" 
        xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        jaxb:version="2.0">
  <annotation>
    <appinfo>
      <jaxb:globalBindings fixedAttributeAsConstantProperty="true" />
    </appinfo>
  </annotation>
  ...
</schema>
Run Code Online (Sandbox Code Playgroud)

2. 通过本地映射:仅定义fixedAttributeAsConstantProperty特定属性上的属性。

<schema targetNamespace="http://stackoverflow.com/example" 
        xmlns="http://www.w3.org/2001/XMLSchema" 
        xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
        xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        jaxb:version="2.0">
    <complexType name="example">
        <attribute name="someconstant" type="xsd:int" fixed="42">
            <annotation>
                <appinfo>
                    <jaxb:property fixedAttributeAsConstantProperty="true" />
                </appinfo>
            </annotation>
        </attribute>
    </complexType>
    ...
</schema>
Run Code Online (Sandbox Code Playgroud)

这两个例子都应该导致:

@XmlRootElement(name = "example")
public class Example {
  @XmlAttribute
  public final static int SOMECONSTANT = 42;
}
Run Code Online (Sandbox Code Playgroud)