读书人

JSR303通译:2.1. Constraint annotat

发布时间: 2012-09-09 09:27:54 作者: rapoo

JSR303翻译:2.1. Constraint annotation(约束注释)
2Constraint Definition(约束定义)
Constraints are defined by the combination of a constraint annotation and a list of constraint validation implementations. The constraint annotation is applied on types, methods, fields or other constraint annotations in case of composition.
约束定义包括一个约束注释和一组约束验证实现。约束注释可以运用于类型,方法,属性和其他的约束注释以便于进行约束组合。
Unless stated otherwise the default package name for the Bean Validation APIs is javax.validation.
如果没有特别说明,Bean Validation APIs的默认的包名是javax.validation。

2.1. Constraint annotation(约束注释)
A constraint on a JavaBean is expressed through one or more annotations. An annotation is considered a constraint definition if its retention policy contains RUNTIME and if the annotation itself is annotated with javax.validation.Constraint.
JavaBean上的一个约束通过一个或者多个注释表示。一个注释就是一个约束定义如果该注释的retention policy包括RUNTIME并且该注释是由javax.validation.Constraint所注释。

/*** Link between a constraint annotation and its constraint validation implementations.*链接一个约束注释和一组约束验证的实现。* <p/>* A given constraint annotation should be annotated by a <code>@Constraint</code>* annotation which refers to its list of constraint validation implementations.*一个约束注释应该由@Constraint所注释,@Constraint会关联一组约束验证的实现。** @author Emmanuel Bernard* @author Gavin King* @author Hardy Ferentschik*/@Documented@Target({ ANNOTATION_TYPE })@Retention(RUNTIME)public @interface Constraint {      /**       * <code>ConstraintValidator</code> classes must reference distinct target types.       * If two <code>ConstraintValidator</code> refer to the same type,       * an exception will occur.       *一个ConstraintValidator类必须引用唯一的目标类型。如果俩个ConstraintValidator       *指向同一个类型,就会产生异常。       * @return array of ConstraintValidator classes implementing the constraint       */         public Class<? extends ConstraintValidator<?, ?>>[] validatedBy();}

Constraint annotations can target any of the following ElementTypes:
? FIELD for constrained attributes
? METHOD for constrained getters
? TYPE for constrained beans
? ANNOTATION_TYPE for constraints composing other constraints
While other ElementTypes are not forbidden, the provider does not have to recognize and process constraints placed on such types. Built-in types do support PARAMETER and CONSTRUCTOR to allow Bean Validation provider specific extensions. It is considered good practice to follow the same approach for custom annotations.
约束注释的target可以为以下元素:
? FIELD 用来约束属性
? METHOD 用来约束get方法
? TYPE 用来约束整个bean
? ANNOTATION_TYPE 用来表示该注释可以用在组合注释里面。
然而,其他的target元素也是允许的,验证提供者不是一定要认识和处理那些taget为其他元素的约束。内置的类型支持 PARAMETER 和CONSTRUCTOR,这样验证框架提供者可以做其他额外的扩展。一个好的实践就是采用和定制注释同样的方法。

Since a given constraint definition applies to one or more specific Java types, the JavaDoc for the constraint annotation should clearly state which types are supported. Applying a constraint annotation to an incompatible type will raise an UnexpectedTypeException. Care should be taken on defining the list of ConstraintValidators. The type resolution algorithm (see Section 3.5.3) could lead to exceptions if the ConstraintValidator list leads to ambiguities.
因为一个约束定义可以运用于一个或者多个java类型,所以这个约束注释的JavaDoc应当清楚的说明哪些类型是支持的。运用一个约束注释到一个该注释不支持的类型上面会产生UnexpectedTypeException异常。应当注意ConstraintValidator列表的定义。类型处理逻辑(see Section 3.5.3)可能导致异常如果ConstraintValidator是有歧义的。

If a constraint definition is not valid, a ConstraintDefinitionException is raised either at validation time or when the metadata is requested. Invalid constraint definitions causes are multiple but include missing or illegal message or groups elements (see Section 2.1.1).
如果约束定义不合法,将会抛出ConstraintDefinitionException异常在验证时或者处理metadata时。非法约束注释包括很多类型,比如约束注释缺少或者包含非法的message或者groups 元素(see Section 2.1.1).
2.1.1. Constraint definition properties(约束定义的属性)
A constraint definition may have attributes that are specified at the time the constraint is applied to a JavaBean. The properties are mapped as annotation elements. The annotation element names message, groups and payload are considered reserved names; annotation elements starting with valid are not allowed; a constraint may use any other element name for its attributes.
约束定义可以包含那些在该约束运用JavaBean时才指定的属性。约束定义的属性会映射到该约束注释的元素。属性名message,groups和payload是系统保留的,并且属性名不能以valid开头,一个约束可以使用其他任何的属性名称作为他的属性。
2.1.1.1. message
Every constraint annotation must define a message element of type String.
String message() default "{com.acme.constraint.MyConstraint.message}";
The message element value is used to create the error message. See Section 4.3 for a detailed explanation. It is recommended to default message values to resource bundle keys to enable internationalization. It is also recommended to use the following convention: the resource bundle key should be the fully qualified class name of the constraint annotation concatenated to .message as shown in the previous program listing.
Built-in Bean Validation constraints follow this convention.
每一个约束注释必须包括message属性,并且该属性为String类型。
String message() default "{com.acme.constraint.MyConstraint.message}";
Message属性值用来产品错误信息,更多信息见Section 4.3,建议message的默认值为资源文件里面的键值,这样可以方便产生国际化的错误信息。像前面的代码一样,同样建议资源文件里面的键值应该由约束注释的完整路径加“.message”组成。
2.1.1.2. groups
Every constraint annotation must define a groups element that specifies the processing groups with which the constraint declaration is associated.
Class<?>[] groups() default {};
The default value must be an empty array.
If no group is specified when declaring the constraint on an element, the Default group is considered declared.See Section 4.1.2 for more information.
Groups are typically used to control the order in which constraints are evaluated, or to perform validation of the partial state of a JavaBean.
每一个约束注释必须包括groups属性,groups属性定义了约束所关联的处理分组。
Class<?>[] groups() default {};
groups的默认值为空数组。
如果在声明这个约束到某一个JavaBean元素时没有定义group,就采用默认值。更多信息见Section 4.1.2。
Groups主要用来控制约束执行的顺序,或者在JavaBean的特定的阶段执行验证。
2.1.1.3. payload
Constraint annotations must define a payload element that specifies the payload with which the the constraint declaration is associated.
Class<? extends Payload>[] payload() default {};
The default value must be an empty array.
约束注释必须定义payload属性,payload属性定义了约束注释所关联payload。payload的默认是值是空数组。

Each attachable payload extends Payload.
所有的使用的payload必须继承Payload接口。
/*** Payload type that can be attached to a given* constraint declaration.* Payloads are typically used to carry on metadata information* consumed by a validation client.** Use of payloads is not considered portable.** @author Emmanuel Bernard* @author Gerhard Petracek*/public interface Payload {}


Payloads are typically used by validation clients to associate some metadata information with a given constraint declaration. Payloads are typically non-portable. Describing payloads as interface extensions as opposed to a stringbased approach allows an easier and more type-safe approach.
One use case for payload shown in Example 2.1 is to associate a severity to a constraint. This severity can be exploited by a presentation framework to adjust how a constraint failure is displayed.
Payload主要用于验证的客户端来关联一些元数据信息到验证声明上面。Payload是不可移植的,采用接口继承来描述payload而不是基于String的方式主要是为了以一种更简单以及类型安全的方式来描述payload。
Example 2.1. Use of payload to associate severity to a constraint使用payload来关联severity到约束
package com.acme.severity;public class Severity {public static class Info implements Payload {};public static class Error implements Payload {};}public class Address {@NotNull(message="would be nice if we had one", payload=Severity.Info.class)public String getZipCode() {...}@NotNull(message="the city is mandatory", payload=Severity.Error.class)String getCity() {...}}


The payload information can be retrieved from error reports via the ConstraintDescriptor either accessed through the ConstraintViolation objects (see Section 4.2) or through the metadata API (see Section 5.5).
通过ConstraintDescriptor在错误报告中获取payload信息既可以使用ConstraintViolation对象 (see Section 4.2) 也可以通过metadata API (see Section 5.5).
2.1.1.4. Constraint specific parameter(约束的定制参数)
The constraint annotation definitions may define additional elements to parameterize the constraint. For example, a constraint that validates the length of a string can use an annotation element named length to specify the maximum length at the time the constraint is declared.
约束注释可以定义其他的属性来定制约束的特性。比如,验证字符串长度的约束可以使用注释属性length来特定的指出某一JavaBean属性允许的最大长度。
2.1.2. Examples
Example 2.2. Simple constraint definition(简单约束定义)
package com.acme.constraint;
/*** Mark a String as representing a well formed order number*/@Documented@Constraint(validatedBy = OrderNumberValidator.class)@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)public @interface OrderNumber {String message() default "{com.acme.constraint.OrderNumber.message}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}


Example 2.2 marks a String as a well-formed order number. The constraint Validator is implemented by OrderNumberValidator.
实例2.2表示一个字符串是格式良好的order number,约束验证由OrderNumberValidator实现。
Example 2.3. Constraint definition with default parameter(包含默认值的约束定义)
package com.acme.constraint;/*** A frequency in Hz as audible to human ear.* Adjustable to the age of the person.* Accept Numbers.*/@Documented@Constraint(validatedBy = AudibleValidator.class)@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)public @interface Audible {Age age() default Age.YOUNG;String message() default "{com.acme.constraint.Audible.message}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};public enum Age {YOUNG,WONDERING,OLD}}

Example 2.3 ensures that a given frequency is within the scope of human ears. The constraint definition includes an optional parameter that may be specified when the constraint is applied.
例2.3确保给定的频率是人们常用的数值。这个约束定义包括一个可选的参数,这个参数可以在使用的时候指定值。
Example 2.4. Constraint definition with mandatory parameter(包含必须参数的约束定义)
package com.acme.constraint;/*** Defines the list of values accepted* Accepts int or Integer objects*/@Documented@Constraint(validatedBy = DiscreteListOfIntegerValidator.class)@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)public @interface Acceptable {int[] value();String message() default "{com.acme.constraint.Acceptable.message}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}

Example 2.4 defines a list of acceptable values expressed as an array: the value property must be specified when the constraint is applied.
实例2.4定义了一组可接受的值,当使用约束的时候必须指定属性值

更多的JSR303翻译将发布在本人主博客上:JSR303翻译 Bean验证框架

读书人网 >网络基础

热点推荐