要自定义校验注解,需要按照以下步骤:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
public @interface CustomValidation {
String message() default "Invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CustomValidator implements ConstraintValidator<CustomValidation, String> {
@Override
public void initialize(CustomValidation constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// 实现自定义的校验逻辑
return value != null && value.startsWith("custom");
}
}
public class User {
@CustomValidation
private String customField;
// getter and setter
}
@Service
public class UserService {
public void createUser(@Validated User user) {
// 业务逻辑
}
}
这样就可以自定义校验注解,并在需要进行校验的地方使用该注解进行自定义的校验逻辑。