SpringBoot - use Assert validation to make business code more concise

Posted by Code_guy on Fri, 25 Feb 2022 03:47:55 +0100

Article catalogue

Pre

SpringBoot - elegant implementation of [parameter verification] advanced

SpringBoot - elegant implementation of [custom parameter verification] advanced

SpringBoot - elegant implementation of [parameter grouping verification] advanced

With the Validator framework, what do you want to do with Assert

In short, Validator only solves the data verification of parameters, but not between parameters and business data

Let's take an example

/**
 * @author Small craftsman
 * @version 1.0
 * @mark: show me the code , change the world
 */

@RestController
@Slf4j 
@RequestMapping("/assert")
public class ArtisanController {

    @Autowired
    private ArtisanDao artisanDao;

    /**
     * Validator It only solves the data verification of the parameter itself, but cannot solve the verification between the parameter and the business data
     *
     * @param
     * @return
     */
    @PostMapping("/testNoAssert")
    public void testNoAssert(@RequestParam("artisanId") String artisanId) {
        Artisan artisan = artisanDao.selectArtisanReturnNull(artisanId);

        if (artisan == null) {
            throw new IllegalArgumentException("user does not exist");
        }

    }

}

We are all familiar with non empty judgment

What about Assert?

    /**
     * Validator It only solves the data verification of the parameter itself, but cannot solve the verification between the parameter and the business data
     *
     * @param
     * @return
     */
    @PostMapping("/testWithAssert")
    public void testWithAssert(@RequestParam("artisanId") String artisanId) {
        Artisan artisan = artisanDao.selectArtisanReturnNull(artisanId);

        Assert.notNull(artisan, "User does not exist( Assert (thrown)");

    }

Do you find that Assert code is more elegant and concise, and can also achieve results

Assert assertion basically replaces the traditional if judgment, reduces the number of code lines for business parameter verification, improves program readability, and likes it~~~

Everyone is using it. Just look for it. I don't believe you see

[return result]

Let's see

The thrown exception is IllegalArgumentException, so handle the global exception

    /**
     * Assert abnormal
     */
    @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseData<String> exception(IllegalArgumentException e) {
        return ResponseData.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), e.getMessage());
    }

Of course, my return result is handled by the global exception. If there is no global exception handling, the original error will be returned

org.springframework.util.Assert

Let's take a look at the methods of asset

Simple classification

Object and type assertions

function

explain

notNull()

Assume that the object is not null

isNull()

The check object is null

isInstanceOf()

The check object must be an instance of another specific type

isAssignable()

Inspection type

Text assertion

function

explain

hasLength()

Check that the string is not an empty string, which means that it contains at least one blank. You can use the hasLength() method

hasText()

Enhance the check condition. The string contains at least one non white space character. You can use the hasText() method

doesNotContain()

The check parameter does not contain a specific substring

Logical assertion

function

explain

isTrue()

If the condition is false, an IllegalArgumentException exception is thrown

state()

This method is the same as isTrue, but throws an IllegalStateException

Collection and map assertions

function

explain

Collection application notEmpty()

The 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 pair)

Array assertion

function

explain

notEmpty()

You can check that the array is not null and contains at least one element

noNullElements()

Ensure that the array does not contain null elements

Source code

https://github.com/yangshangwei/boot2