要自定義校驗注解,需要按照以下步驟:
@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) {
// 業務邏輯
}
}
這樣就可以自定義校驗注解,并在需要進行校驗的地方使用該注解進行自定義的校驗邏輯。