0 day streak
java / intermediate
Snippet

Method-Level Validation with @Validated

Spring supports JSR-303 Bean Validation at the method level. By adding @Validated to the class, Spring will throw a ConstraintViolationException if parameters are invalid.

snippet.java
java
1
2
3
4
5
6
7
@Service
@Validated
public class UserService {
public void updateUser(@NotBlank String username, @Min(18) int age) {
// Logic to update user
}
}
spring
Breakdown
1
@Validated
Enables constraint checking for method parameters within this component.
2
@NotBlank String username
Ensures the username is not null and contains at least one non-whitespace character.
3
@Min(18) int age
Requires the age parameter to be at least 18.