This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

In the course of a Spring Boot development project, we can often use some annotations to make our code look more elegant and efficient. The following section will introduce some of these annotations.

@Valid

When writing business code, you have to check the parameters from the front end. Although the front end usually verifies the page input once, to ensure the robustness of the functionality, the back end needs to verify again when receiving the front end parameters. If it’s just one or two parameters, it’s easy to write, usually just a few if’s, it looks pretty neat. But when a form is submitted with more than a dozen parameters, each with an if validation, I’m afraid the technical manager’s face will be distorted when reviewing the code. Let’s take a look at the @Valid annotation to see how it can help us eliminate these bloated validations. First, we introduce dependencies into the project

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.01..Final</version>
</dependency>
 
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.41..Final</version>
</dependency>
Copy the code

Then you can happily use the correlation validation annotation in your project

/** * Chain name */
@NotBlank(message = "{required}")
@Size(max = 100, message = "{noMoreThan}")
private String chainName;

/** * Chain id */
@NotBlank(message = "{required}")
@Size(max = 100, message = "{noMoreThan}")
private String chainId;
Copy the code

As you can see, we added @Notblank and @size to the field to verify non-null and field length, respectively. Finally, we add @valid to the controller to validate the validation.

After writing this, it feels like the whole code is much cleaner, no more writing the headache of if validation. Of course,@validSupports quite a bit of field validation logic in

Note the name meaning
@NotBlan It must not be empty
@Size Length check, which can add Max and min
@URL It must be a URL
@Email Must be a properly formed email address
@Pattern Conforms to the specified regular expression
See the annotations already in the JAR for more information

conclusion

With such a simple annotation, we can make our code look more concise and make the validation logic more clear. So when we write functionality, we can think more about how to implement it with less code and avoid bloated code piling up in the project.