私は Java EE 6+ に付随する Bean Validation API について多くのことを読んでいて、検証 API がどのように機能するかの基本を理解していますが、私が読んでいるドキュメントでは、すべての例は単体テストであり、検証操作を実装する場所を理解するのに役立ちます。
私は 3 層アーキテクチャ システムを開発しています。検証をサービス層に配置したいので、プレゼンテーション層が異なる場合 (つまり、Jax-RS、JSF など) に検証コードを再利用できます。しかし、私は上記の操作を実装する方法について混乱しています。これが私が立ち往生している場所です:
モデル内のさまざまなエンティティと対話する Bean があります。たとえば、これはユーザー インタラクション用の Bean 内のメソッドです ->
public User getUser(
@Min(value = 0, message = "Must have a positive userId") int uid)
throws RetrievalNotFoundException {
try {
// I WANT TO VALIDATE UID HERE
// find User with provided uid
User foundUser = em.find(User.class, uid);
// IF the user is inactive
if (foundUser.getIsActive() == 0) {
// cannot find the content
throw new RetrievalNotFoundException();
}
// close the entity manager
em.close();
// return the user
return foundUser;
}
休止状態のドキュメントの例を次に示します。
Car object = new Car( "Morris" );
Method method = Car.class.getMethod( "drive", int.class );
Object[] parameterValues = { 80 };
Set<ConstraintViolation<Car>> violations = executableValidator.validateParameters(
object,
method,
parameterValues
);
assertEquals( 1, violations.size() );
Class<? extends Annotation> constraintType = violations.iterator()
.next()
.getConstraintDescriptor()
.getAnnotation()
.annotationType();
assertEquals( Max.class, constraintType );
メソッド getUser() にアクセスするために、Bean を再度インスタンス化する必要があるのでしょうか。私は混乱しています。私が持っていた別の質問は、誰かが int コンテナーをオーバーフローする uid の int を入れることにした場合はどうなるかということでした。どうすればそれを検証できますか?
本当にありがとうございました。