2016-05-09 51 views
4

我目前正在其上使用以下contruct一个XSD:JAXB:生成固定值属性定值

<xs:attribute name="listVersionID" type="xs:normalizedString" use="required" fixed="1.0"> 

虽然不是问题本身,这是相当恼人的工作,因为此定义的固定值在xsd规范的版本之间增加,我们需要修改单独的常量类中的值以保持它们的有效性,尽管xsd中的任何兴趣都没有改变。 xsd在别处维护,所以只是改变它是不行的。

因此我问自己阉有一个JAXB的插件或类似转动固定值属性插入常量的ala

@XmlAttribute(name = "listVersionID") 
@XmlJavaTypeAdapter(NormalizedStringAdapter.class) 
@XmlSchemaType(name = "normalizedString") 
protected final String listVersionID = "1.0"; 

,而不是仅仅

@XmlAttribute(name = "listVersionID") 
@XmlJavaTypeAdapter(NormalizedStringAdapter.class) 
@XmlSchemaType(name = "normalizedString") 
protected String listVersionID; 

必须手动填充。

有没有人知道这样的?

回答

3

是的,它可以通过自定义的jaxb绑定,它可以作为codegen中的文件添加。

在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> 

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> 

两个例子都应该导致:

@XmlRootElement(name = "example") 
public class Example { 
    @XmlAttribute 
    public final static int SOMECONSTANT = 42; 
} 
3

如果你不想修改你的模式,另一种选择是使用外部绑定文件

<?xml version="1.0" encoding="UTF-8"?> 
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
    version="2.0" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"> 

    <jaxb:bindings schemaLocation="yourschema.xsd" node="/xs:schema"> 
    <jaxb:globalBindings fixedAttributeAsConstantProperty="true" /> 
    </jaxb:bindings> 

</jaxb:bindings> 

这相当于在他的回答中提出了@jmattheis。