完成包
如许多其它开放源码软件,在这里显示的数据绑定包是一项正在进行中的工作。虽然它已经初具规模,但仍有很大空间可用于添加更多功能和做改进。因此,以这段代码为基础,可以有许多方式应用程序中加以衍生。
可以重新使用该样本代码,以将 XML schema 的数据约束转换为类型安全的 Java 接口和实现。例如,迄今为止,示例代码还没有处理 XML schema 中可能指定的范围。而对于许多 XML 开发人员,那些数据范围才是使用 schema 的真正原因。然后,请考虑清单 6 中 Web 服务的扩充 XML schema。
清单 6. 带扩充约束的 Web 服务配置
<?xml version="1.0"?>
<schema targetNamespace="http://www.enhydra.org"
xmlns="http://www.w3.org/1999/xmlSchema"
xmlns:enhydra="http://www.enhydra.org"
>
<complexType name="ServiceConfiguration">
<attribute name="name" type="string" />
<attribute name="version" type="float" />
</complexType>
<element name="serviceConfiguration" type="ServiceConfiguration" />
<complexType name="WebServiceConfiguration"
baseType="ServiceConfiguration"
derivedBy="extension">
<element name="port">
<complexType>
<attribute name="protocol" type="string" />
<attribute name="number">
<simpleType base="integer">
<minExclusive value="0" />
<maxInclusive value="32767" />
</simpleType>
</attribute>
<attribute name="protected" type="string" />
</complexType>
</element>
<element name="document">
<complexType>
<attribute name="root" type="string" />
<attribute name="index" type="string" />
<attribute name="error" type="string" />
</complexType>
</element>
</complexType>
<element name="webServiceConfiguration" type="WebServiceConfiguration" />
</schema>
清单 6 说明了 number 属性的类型,并且在用红色强调的几行中指定了值的合法范围(1 到 32,767)。当前版本的 SchemaMapper 将忽略这些附加声明。从 schema 创建 Java 接口和实现类时,没有必要处理 XML schema 中的 minXXX 和 maxXXX 关键字,但它们可以增加相当多的附加验证。
请查看清单 7 中的代码示例,这些代码是可在实现类中生成的代码,以确保只有 schema 指定范围中的值可以作为变量。
清单 7. 带范围检查的生成代码
public class PortTypeImpl implements PortType {
private String protocol;
private int number;
private String protected;
public void setNumber(int number) {