この記事では、Spring で @RequestBody アノテーションが付けられたエンティティ クラスのすべてのパラメーターが null でないことを確認する方法について説明します。 null パラメーターに対する @RequestBody のデフォルトの動作について説明し、null パラメーターを処理するためのいくつかのオプションを提供します

@RequestBody アノテーションが付けられたエンティティ クラスが null でない場合は、javax.validationパッケージの@NotNullアノテーションを使用できます。 アノテーションがフィールドに適用されると、Spring Validation はフィールドが null でないかどうかを自動的にチェックします。 null の場合、ConstraintViolationExceptionがスローされます。@NotNullannotation from thejavax.validationpackage.
import javax.validation.constraints.NotNull; public class MyEntity { @NotNull private String name; // Other fields }
When the@NotNullannotation is applied to a field, Spring Validation will automatically check if the field is non-null. If it is null, aConstraintViolationExceptionwill be thrown.
By default, @RequestBody will bind a null value to a non-primitive field in the entity class. For example, if you have a field annotated with@RequestBodyand the corresponding request parameter is null, the field will be set to null in the entity class.
You have several options to handle the situation when some parameters in an entity class with @RequestBody are null:
@DefaultValueannotation from thejavax.validationpackage.import javax.validation.constraints.DefaultValue; public class MyEntity { @RequestBody private String name; @DefaultValue("unknown") private String description; // Other fields }
In this case, if thedescriptionparameter is null in the request, it will be set to "unknown" in the entity class.
Optionalwrapper class from thejava.utilpackage.import java.util.Optional; public class MyEntity { @RequestBody private String name; private Optional description; // Other fields }
In this case, if thedescriptionparameter is null in the request, thedescriptionfield in the entity class will be set toOptional.empty().
BadRequestException@RequestBodyの注釈が付けられたフィールドがあり、対応するリクエスト パラメーターが null の場合、そのフィールドはエンティティ クラスで null に設定されます。 @RequestBody を使用したエンティティ クラス?@RequestBody を使用したエンティティ クラスの一部のパラメーターが null の場合に状況を処理するためのオプションがいくつかあります:
javax.validationパッケージの@DefaultValueアノテーションを使用して、null フィールドのデフォルト値を設定します。rrreeeこの場合、descriptionパラメータがリクエストで null の場合、エンティティ クラスで「unknown」に設定されます。
java.utilパッケージのOptionalラッパー クラスを使用するエンティティ クラス。rrreee この場合、descriptionパラメーターが null の場合、リクエストでは、エンティティ クラスのdescriptionフィールドがOptional.empty()に設定されます。
BadRequestExceptionをスローできます。以上がSpring で @RequestBody アノテーションを使用して受信したエンティティ クラスの一部のパラメーターが null ですの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。