Bean Validation その1

Chapter 2. Constraint 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 APIのデフォルトパッケージ名は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が設定されており、さらに制約検証の実装リストを参照しています。
 *
 * @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.
     *
   ConstraintValiatorクラスは重複の無い型を参照しているべきであり、
   もし、同じ型を参照していた場合は例外が発生します。
     * @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.

その他のElementTypes使用を禁じてないならば、プロバイダーはそのようなタイプの制約を処理する必要はありません。Bean Validationは組み込みとして特定制約を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, “ConstraintValidator resolution algorithm”) could lead to exceptions if the ConstraintValidator list leads to ambiguities.

制約定義は一つまたはそれ以上のJavaの型について適用され、JavaDocにどの型をサポートしているか明確に示すべきです。
制約の適用が非互換の型であればUnexpectedTypeExceptionが発生します。
そのため、ConstraintValidatorのリストには十分気をつけるべきです。

型の解決アルゴリズムで(Section3.5.3 制約検証解決アルゴリズム)曖昧な制約検証リストが導かれた場合、例外の発生となります。

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, “Constraint definition properties”).

制約定義が不適な場合、制約定義例外が検証時かまたはメタデータの解析時に発生します。
不適な制約定義はメッセージやグループプロパティが無い等複数あります。(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が注釈要素名として予約されています。
上記の要素が無い場合、注釈要素として有効になりません。
制約の属性にそれ以外の要素名を使用するようにして下さい。

2.1.1.1. message

メッセージ

Every constraint annotation must define a message element of type String.

全ての制約注釈はString型のmessage要素が定義されるべきです。

String message() default "{com.acme.constraint.MyConstraint.message}";

The message element value is used to create the error message. See Section 4.3, “Message interpolation” 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.

message要素値は詳細説明の為のエラーメッセージ生成に使用されます。(Section4.3 メッセージ挿入 参照 )
デフォルトメッセージ値は国際化仕様のリソースバンドルキーがおすすめです。
さらに、続く規約を利用する事も推奨します。
:リソースバンドルキーは前述のmessage要素値のような制約注釈クラスの完全修飾名に.messageを連結した値であるべきです。

Built-in Bean Validation constraints follow this convention.

組み込みのBean Validation制約はこの規約に従っています。

2.1.1.2. groups

groups

Every constraint annotation must define a groups element that specifies the processing groups with which the constraint declaration is associated.

全ての制約注釈はgroups要素が定義されるべきです。
これは関連した制約宣言をグループ単位の処理する為の規定です。

    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.

もし、groupの値が空であった場合はDefaultグループを宣言したことと規定します。

See Section 4.1.2, “groups” for more information.

Section 4.1.2 groups より詳しい情報

Groups are typically used to control the order in which constraints are evaluated, or to perform validation of the partial state of a JavaBean.

グループは制約処理の評価を制御することやJavaBeanの状態により部分的な検証を行うことに使用されます。

2.1.1.3. payload

荷重

Constraint annotations must define a payload element that specifies the payload with which the constraint declaration is associated.

制約注釈はpayload要素が定義されるべきです。
これは関連した制約宣言に荷重を与えるための規定です。

    Class<? extends Payload>[] payload() default {};

The default value must be an empty array.

デフォルト値は空の配列です。

Each attachable payload extends Payload.

それぞれの荷重はPayloadインターフェースを継承しています。

/**
 * Payload type that can be attached to a given
 * constraint declaration.
Payloadは制約宣言から継承されます。
 * 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 string-based approach allows an easier and more type-safe approach.

荷重は与えられた制約定義のメタデータ情報をクライアント関連づけするために使われます。
荷重は個別使用を想定してません。
Stringベースと対照的にインタフェース拡張としてペイロードを記述する方がより簡単でまた、タイプセーフなアプローチです。

One use case for payload shown in Example 2.1, “Use of payload to associate severity to a constraint” 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.

荷重の一つの例としてExample 2.1を示します。
”制約と重大度の関連のための荷重使用”は制約に対する重大度を関連づけます。
この重大度はpresentation frameworkにて制約不適を表示するかどうかの調整
に使用することができます。

Example 2.1. Use of payload to associate severity to a constraint

制約と重大度の関連のための荷重使用

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, “ConstraintViolation”) or through the metadata API (see Section 5.5, “ConstraintDescriptor”).

荷重情報はConstraintViolationオブジェクトに含まれるConstraintDescriptorでのエラーリポートから検索利用することができます。 (Section 4.2, “ConstraintViolation”参照) 、 ( Section 5.5, “ConstraintDescriptor”参照).