JAXB是否支持xsd:restriction?

Nar*_*hai 21 java web-services jaxb java-ee xsd-validation

<xs:element name="age">
  <xs:simpleType>
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="0"/>
      <xs:maxInclusive value="120"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>
Run Code Online (Sandbox Code Playgroud)

所以我希望它像这样转换为Java代码:

public void setAge(int age){
    if(age < 0 || age > 120){
         //throw some exception
    }
     //setting the age as it is a valid value
}
Run Code Online (Sandbox Code Playgroud)

在JAXB中可以吗?

曾经看过一些WebService Client存根生成器这样做可能是axis2 webservice但不确定.

bdo*_*han 20

JAXB(JSR-222)规范不包括生成快速失败逻辑到域模型.现在通常的做法是以注释(或XML)的形式表示验证规则并对它们运行验证. Bean Validation(JSR-303)对此进行了标准化,并且可用于任何Java EE 6实现.

XJC扩展

我自己没有尝试过以下扩展,但似乎它会从XML模式生成对域模型表示验证规则的Bean Validation(JSR-303)注释.由于XJC非常易于扩展,因此可能还有其他插件可用.

  • @NarendraPathai - 这是我第一次听说过JAXB Facets.这当前不是JSR的一部分,并且被提议作为JAXB参考实现的增强.我发表了一篇关于JIRA问题的评论,询问它与Bean Validation(JSR-303)的兼容性.JSR-303兼容方法可以在未来版本的JAXB规范中得到支持. (2认同)

Dru*_*nix 5

在JAXB中执行此验证的建议方法是在marshaller resp上打开模式验证。解组员:

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = schemaFactory.newSchema(...);

ValidationEventHandler valHandler = new ValidationEventHandler() {
  public boolean handleEvent(ValidationEvent event) {
      ...
  }
};

marshaller.setSchema(schema);
marshaller.setEventHandler(valHandler);
Run Code Online (Sandbox Code Playgroud)


vbe*_*nce 5

你可以试试JAXB-Facets。快速片段:

class MyClass {

    @MinOccurs(1) @MaxOccurs(10)
    @Facets(minInclusive=-100, maxInclusive=100)
    public List<Integer> value;

    @Facets(pattern="[a-z][a-z0-9]{0,4}")
    public String name;

}
Run Code Online (Sandbox Code Playgroud)