Springで@Requiredスタイルのカスタムアノテーションを定義する
@Required annotationは、特定のプロパティが設定されていることを確認するために使用されます。 既存のプロジェクトをSpringフレームワークに移行する場合、または何らかの理由で独自の@ Required-styleアノテーションを使用する場合、Springでは@Requiredアノテーションと同等のカスタム@ Required-styleアノテーションを定義できます。
この例では、@Requiredアノテーションと同等の@Mandatoryという名前のカスタム@Required-styleアノテーションを作成します。
1. @Mandatoryインターフェースを作成する
package com.example.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Mandatory {
}
2. プロパティに適用する
package com.example.common;
public class Customer
{
private Person person;
private int type;
private String action;
@Mandatory
public void setPerson(Person person) {
this.person = person;
}
//getter and setter methods
}
3. 登録する
新しい@Mandatoryアノテーションを「RequiredAnnotationBeanPostProcessor」クラスに含めます。
4. Done
これで、@Mandatoryという名前の新しいカスタム@Requiredスタイルのアノテーションが作成されました。これは@Requiredアノテーションと同等です。