Spring中@NotBlank注解无法使用问题求助
Hey, let's work through this @NotBlank issue step by step. I've dealt with similar problems before, so here are some additional checks and fixes you can try:
Ensure you're using @Valid or @Validated on your controller parameter
This is a super common oversight! Even with the validation dependency and annotations on your entity, Spring won't trigger validation unless you mark the incoming request body (or parameter) with either@Valid(JSR-380 standard) or@Validated(Spring's extended version that supports validation groups). Here's an example:@PostMapping("/users") public ResponseEntity<?> createUser(@Valid @RequestBody User user) { // Your logic here }Verify your annotation import (and consider switching to jakarta for Spring Boot 2.7.x)
While Spring Boot 2.7.x still supportsjavax.validation.constraints.NotBlank, there can be dependency conflicts if other libraries in your project pull in jakarta.validation. Try switching to the jakarta variant:import jakarta.validation.constraints.NotBlank;The
spring-boot-starter-validationalready includes all necessary dependencies (like Hibernate Validator) for this to work, so you don't need to add anything extra.Check if validation is enabled in your application config
Double-check yourapplication.propertiesorapplication.ymlto make sure you haven't accidentally disabled validation:# Make sure this is either true or removed (default is true) spring.validation.enabled=trueValidate your entity class setup
@NotBlankonly works on String fields — if you're using it on non-String types (like Integer, Boolean), it won't work. Use@NotNullfor non-String nullable fields instead.- Ensure your entity fields have proper access: if fields are
private, make sure you have getter methods (validation frameworks need to access field values to perform checks).
Check for custom validator configurations
If you've added any customValidatorbeans orValidationConfigurationclasses in your project, they might be overriding the default validation setup. Review these classes to make sure they aren't disabling or replacing the default validator behavior.Clean and rebuild your project (with Maven cache refresh)
Sometimes corrupted dependency caches can cause issues. Run these commands in your project root:mvn clean install -UThe
-Uflag forces Maven to update snapshot dependencies. After this, restart your IDE and re-run the application.
内容的提问来源于stack exchange,提问作者Ntavass

