Java 有没有一种方法可以在没有getter方法的情况下抛出自定义验证器拒绝值?
我目前正在研究用Spring构建API。我正在使用SpringValidator来验证我的输入。这是我的自定义验证器:Java 有没有一种方法可以在没有getter方法的情况下抛出自定义验证器拒绝值?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我目前正在研究用Spring构建API。我正在使用SpringValidator来验证我的输入。这是我的自定义验证器: public class NewHoldValidator implements Validator { private EntityManager manager; public NewHoldValidator(EntityManager manager) { this.manager = manager; } @Ove
public class NewHoldValidator implements Validator {
private EntityManager manager;
public NewHoldValidator(EntityManager manager) {
this.manager = manager;
}
@Override
public boolean supports(Class<?> clazz) {
return NewHoldRequest.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
if (errors.hasErrors()) {
return;
}
NewHoldRequest request = (NewHoldRequest) target;
Patron patron = manager.find(Patron.class, request.patronId);
BookInstance bookInstance = manager.find(BookInstance.class, request.bookInstanceId);
Assert.state(patron != null, "Patron does not exists.");
Assert.state(bookInstance != null, "Book instance does not exists.");
if (!bookInstance.acceptToBeHoldTo(patron)) {
errors.reject(null, "This book instance cannot be hold to this patron");
}
if (!request.hasDaysHold()) {
if (!patron.researcher()) {
errors.rejectValue("daysHold", null, "You need to pass a daysHold attribute");
}
}
}
}
即使我的字段“daysHold”是公共的,我仍然需要为它创建一个getter,以便Spring能够正确地显示被拒绝的错误,否则,它将抛出一个NotReadablePropertyException。有没有一种方法可以定义Spring可以拒绝没有getter的公共字段,或者我需要向我想要拒绝的所有字段添加访问器方法
以下是触发我的验证时显示的消息
org.springframework.beans.NotReadablePropertyException: Invalid property 'daysHold' of bean class [com.api.library.usecases.newhold.NewHoldRequest]: Bean property 'daysHold' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
我建议您使用界面
ConstraintValidator
。这是一个通用的接口,没有铸造和其他问题。
您应该为自己创建一个自定义约束注释,在实现CustomValidator接口之后为@NewHoldValid:
@Component
public class NewHoldValidator implements ConstraintValidator<NewHoldValid, NewHoldRequest> {
@Override
public boolean isValid(NewHoldRequest value, ConstraintValidatorContext context) {
if(ANY_CONDITION){
return true;
}else {
return false;
}
}
@Component
public class NewHoldValidator implements ConstraintValidator<NewHoldValid, NewHoldRequest> {
@Override
public boolean isValid(NewHoldRequest value, ConstraintValidatorContext context) {
if(ANY_CONDITION){
return true;
}else {
return false;
}
}
context.buildConstraintViolationWithTemplate("Your error message").addConstraintViolation();