38.5. 自定义修复的值属性映射
概述
默认情况下,代码生成器映射属性定义为具有固定值到普通属性。使用模式验证时,Apache CXF 可以强制使用模式定义(请参阅 第 24.3.4.7 节 “模式验证类型值”)。但是,使用模式验证会增加消息处理时间。
将固定值的属性映射到 Java 的另一种方法是将它们映射到 Java 常数。您可以使用 globalBindings 自定义元素指示代码生成器将固定值属性映射到 Java 常数。您还可以使用 property 元素自定义固定值属性到 Java 常量的映射。
全局自定义
您可以通过添加 globalBinding 元素的 fixedAttributeAsConstantProperty 属性来更改此行为。将此属性设置为 true 会指示代码生成器将任何使用 fixed 属性定义的属性映射到 Java 常量。
例 38.21 “用于强制生成 Constants 的 in-Line 自定义” 显示一行自定义,它会强制代码生成器为带有固定值的属性生成常量。
例 38.21. 用于强制生成 Constants 的 in-Line 自定义
<schema targetNamespace="http://widget.com/types/widgetTypes"
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>例 38.22 “绑定文件以强制生成 Constants” 显示自定义固定属性生成的外部绑定文件。
例 38.22. 绑定文件以强制生成 Constants
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.0">
<jaxb:bindings schemaLocation="types.xsd">
<jaxb:globalBindings fixedAttributeAsConstantProperty="true" />
<jaxb:bindings>
<jaxb:bindings>本地映射
您可以使用 property 元素的 fixedAttributeAsConstantProperty 属性根据每个属性自定义属性映射。将此属性设置为 true 会指示代码生成器将任何使用 fixed 属性定义的属性映射到 Java 常量。
例 38.23 “用于强制生成 Constants 的 in-Line 自定义” 显示一行自定义,它会强制代码生成器为带有固定值的单个属性生成常量。
例 38.23. 用于强制生成 Constants 的 in-Line 自定义
<schema targetNamespace="http://widget.com/types/widgetTypes"
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="widgetAttr">
<sequence>
...
</sequence>
<attribute name="fixer" type="xsd:int" fixed="7">
<annotation> <appinfo> <jaxb:property fixedAttributeAsConstantProperty="true" /> </appinfo> </annotation>
</attribute>
</complexType>
...
</schema>例 38.24 “绑定文件以强制生成 Constants” 显示自定义固定属性生成的外部绑定文件。
例 38.24. 绑定文件以强制生成 Constants
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.0">
<jaxb:bindings schemaLocation="types.xsd">
<jaxb:bindings node="xsd:complexType[@name='widgetAttr']">
<jaxb:bindings node="xsd:attribute[@name='fixer']">
<jaxb:property fixedAttributeAsConstantProperty="true" />
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
<jaxb:bindings>Java 映射
在默认映射中,所有属性都通过 getter 和 setter 方法映射到标准 Java 属性。当此自定义应用于使用 fixed 属性定义的属性时,属性映射到 Java 常数,如 例 38.25 “将固定值属性映射到 Java Constant” 所示。
例 38.25. 将固定值属性映射到 Java Constant
@XmlAttribute public final static type NAME = value;
类型 是通过使用 第 34.1 节 “原语类型” 中描述的映射将属性的基本类型映射到 Java 类型来确定。
NAME 通过将 attribute 元素的 name 属性的值转换为所有大写字母来确定。
值 由 attribute 元素 的固定 属性的值决定。
例如,例 38.23 “用于强制生成 Constants 的 in-Line 自定义” 中定义的属性映射,如 例 38.26 “修复了映射到 Java Constant 的值属性” 所示。
例 38.26. 修复了映射到 Java Constant 的值属性
@XmlRootElement(name = "widgetAttr")
public class WidgetAttr {
...
@XmlAttribute
public final static int FIXER = 7;
...
}