Why Use Assert with Spring Validator? A Comparison and Usage Guide
This article explains that while Spring's Validator handles simple parameter validation, it cannot validate relationships between parameters and business data, and demonstrates how using org.springframework.util.Assert provides a more concise, readable way to perform such checks, including exception handling examples.
Why Use Assert with Spring Validator?
In short, Validator only solves the data validation of the parameter itself and cannot handle validation between the parameter and business data.
Let's look at an example.
@RestController
@Slf4j
@RequestMapping("/assert")
public class ArtisanController {
@Autowired
private ArtisanDao artisanDao;
/**
* Validator only solves the data validation of the parameter itself, cannot solve validation between parameter and business data
*/
@PostMapping("/testNoAssert")
public void testNoAssert(@RequestParam("artisanId") String artisanId) {
Artisan artisan = artisanDao.selectArtisanReturnNull(artisanId);
if (artisan == null) {
throw new IllegalArgumentException("用户不存在");
}
}
}Non‑null checks are familiar to everyone.
How would this look using Assert?
@PostMapping("/testWithAssert")
public void testWithAssert(@RequestParam("artisanId") String artisanId) {
Artisan artisan = artisanDao.selectArtisanReturnNull(artisanId);
Assert.notNull(artisan, "用户不存在(Assert抛出)");
}Notice that the Assert version is more elegant and concise while achieving the same effect.
Assert assertions basically replace traditional if‑statements, reducing the number of lines needed for business parameter validation and improving code readability – thumbs up!
Everyone uses it; just search and you’ll see many examples.
Return Result
Let's take a look.
The exception thrown is IllegalArgumentException , so it should be handled globally.
@ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseData
exception(IllegalArgumentException e) {
return ResponseData.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), e.getMessage());
}In my case the result is processed by a global exception handler; without it the raw error would be returned.
org.springframework.util.Assert
Let's see what methods Assert provides.
They can be roughly classified as:
Object and Type Assertions
Text Assertions
Logic Assertions
Collection and Map Assertions
Array Assertions
Source Code
https://github.com/yangshangwei/boot2
Thank you for reading, hope it helps :)
Source: artisan.blog.csdn.net/article/details/123105926
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.