SpringBoot parameter verification Assert use

foreword

assert: Assertion is a reserved word in java, used to debug programs, followed by logical operation expressions, as follows:

int a = 0, b = 1;
assert a == 0 && b == 0;
How to use: javac compile the source file, and then java -ea class file name.
In springboot, you can use the method of the Assert class provided by spring to verify the parameters from the front end

Assert assertions basically replace the traditional if judgment, reduce the number of lines of code for business parameter verification, and improve program readability.

@Validated, @Valid comparison and detailed usage

The Validator framework was introduced earlier, do you still need Assert?
Validator only solves the data verification of the parameter itself, and cannot solve the verification between the parameter and the business data

Example:

    /**
     * Validator只解决了参数自身的数据校验,解决不了参数和业务数据之间校验
     *
     * @param
     * @return
     */
    @PostMapping("/testWithAssert")
    public void testWithAssert(@RequestParam("artisanId") String artisanId) {
        Artisan artisan = artisanDao.selectArtisanReturnNull(artisanId);

        Assert.notNull(artisan, "用户不存在(Assert抛出)");

    }

Assert code is more elegant and concise, and the same effect can be achieved.

What are the methods of Assert

Object and Type Assertion

function illustrate
notNull() Assume the object is not null
isNull() check object is null
isInstanceOf() Checks that the object must be an instance of another specific type
isAssignable() Check type

text assertion

function illustrate
hasLength() To check that the string is not an empty string, which means it contains at least one blank, you can use the hasLength() method
hasText() Enhance the check condition, the string contains at least one non-whitespace character, you can use the hasText() method
doesNotContain() Check parameter does not contain specific substring

logical assertion

function illustrate
isTrue() Throws IllegalArgumentException if the condition is false
state() This method is the same as isTrue, but throws an IllegalStateException

Collection and map assertions

function illustrate
Collection application notEmpty() Collection is not null and contains at least one element
map application notEmpty() Check that the map is not null and contains at least one entry (key, value key-value pair)

array assertion

function illustrate
notEmpty() You can check that the array is not null and contains at least one element
noNullElements() Make sure the array does not contain null elements

Guess you like

Origin blog.csdn.net/liuerchong/article/details/123941602