我有一个这样的REST api:
0.toFixed(2) === "0.00"
输入存储在这个bean中:
@POST
@Path("/dopost")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public String doPostExample(@Valid @BeanParam final DemoBean demo) {
return "done";
}
由于我想一起验证一组字段(与位置相关),我创建了一个类级验证器。
这是我创建的注释:
@Address
public class DemoBean {
private String address;
private String city;
// Other member variables
// getters and setters
}
这里有验证器:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = AddressValidator.class)
@Documented
public @interface Address {
String message() default "{com.mycompany.constraints.checkcase}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
然而,某些事情必定是非常错误的,因为它不起作用。我在日志中得到了这个堆栈跟踪:
public class AddressValidator implements ConstraintValidator<Address, Address> {
public void initialize(Address constraintAnnotation) {
// initialize the zipcode/city/country correlation service
}
@Override
public boolean isValid(Address address, ConstraintValidatorContext constraintValidatorContext) {
return true; // I put a breakpoint here, but it doesn't stop here and I have the stack trace below
}
}
答案 0 :(得分:1)
问题在于您的AddressValidator
课程。两个通用参数ConstraintValidator<Address, Address>
都引用您的Adress
注释类。这是不正确的。第一个参数应该是你的注释,第二个参数应该是你的DemoBean,如下所示。
public class AddressValidator implements ConstraintValidator<Address, DemoBean> {
public void initialize(Address constraintAnnotation) {
// initialize the zipcode/city/country correlation service
}
@Override
public boolean isValid(DemoBean addressBean, ConstraintValidatorContext constraintValidatorContext) {
return true;
}
}