Get the App
SLTechnology News&Howtos  ›  Development  › 

How to validate custom comments for input requests in SpringBoot

Shulou Source: shulou.com Published: 2022-06-01 12:07:30 10月03日 Update

This article mainly introduces how to verify the custom comments of the input request in SpringBoot, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.

In our daily programming, we use many Spring Boot default annotations that can be used for validation, such as @ NotNull, @ Size, @ NotBlank, @ Digits, and so on, which is a cool way to validate any incoming requirements.

Consider a scenario where some fields are optional by default and must be mandatory if others are populated with specific values.

Spring does not have predefined comments for this kind of validation.

Let's give some examples of how we can simplify the validation process, make its code reusable, and introduce abstraction at the annotation level.

In a typical sales platform, there will be sales operations and invalid sales operations. This amount is mandatory in the sales operation, and if the sales operation is invalid, the write-off type will be mandatory.

Our dto class is as follows:

Public class IncomingRequestDto {public TransactionType transactionType; public ReversalType reversalType; public String reversalId; public AmountDto amountDto;}

IncomingRequestDto has several properties, such as transactionType and reversalType as ENUMS.

Public enum TransactionType {SALE {public String toString () {return "Sale";}}, VOIDSALE {public String toString () {return "VoidSale";}},} public enum ReversalType {TIMEDOUT {public final String toString () {return "Timedout" }, CANCELLED {public final String toString () {return "Cancelled";}

And amountDto are:

Public class AmountDto {public String value;}

Scenario 1: amountDto.value is conditional. When we receive a request with transactionType= "SALE", amountDto.value should be mandatory.

Scenario 2: reversalType is conditional. When we receive a request with transactionType= "VOIDSALE", reversalType should be mandatory.

Let's first define a comment with the attributes required for the validation process:

@ Target ({TYPE, ANNOTATION_TYPE}) @ Retention (RUNTIME) @ Documentedpublic @ interface NotNullIfAnotherFieldHasValue {String fieldName (); String fieldValue (); String dependFieldName (); String message (); Class [] groups () default {}; Class

Tags: Validation sales mandatory mandatory annotations comments articles scenarios input code fields properties situations conditions types procedures search value examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Docker MySQL Shulou Technology