编程语言
首页 > 编程语言> > java – Spring验证器:同时具有注释和验证器实现

java – Spring验证器:同时具有注释和验证器实现

作者:互联网

是否可以同时为表单和注释约束提供验证器?

例如,在表单对象中包含此字段:

@NotEmpty
private String date;

但然后在验证器中验证日期的模式.

我知道有模式注释,但我只是想看看我是否可以使用这两种类型的验证.

解决方法:

Here是一个非常好的网站链接,它解释了如何将JSR-303验证器与弹簧验证器结合起来.

接下来我将介绍我的解决方案.希望能帮助到你.

我的抽象确认者:

import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.validation.Errors;


public abstract class AbstractValidator implements org.springframework.validation.Validator, ApplicationContextAware,
    ConstraintValidatorFactory {

@Autowired
private Validator validator;

private ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
}

public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    Map<String, T> beansByNames = applicationContext.getBeansOfType(key);
    if (beansByNames.isEmpty()) {
        try {
            return key.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("Could not instantiate constraint validator class '" + key.getName() + "'", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Could not instantiate constraint validator class '" + key.getName() + "'", e);
        }
    }
    if (beansByNames.size() > 1) {
        throw new RuntimeException("Only one bean of type '" + key.getName() + "' is allowed in the application context");
    }
    return (T) beansByNames.values().iterator().next();
}

public boolean supports(Class<?> c) {
    return true;
}

public void validate(Object objectForm, Errors errors) {
    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(objectForm);
    for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
        String propertyPath = constraintViolation.getPropertyPath().toString();
        String message = constraintViolation.getMessage();
        errors.rejectValue(propertyPath, "", message);
    }
    addExtraValidation(objectForm, errors);
}

protected abstract void addExtraValidation(Object objectForm, Errors errors);

}

一个实际的验证者:

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import ro.scorpionsoftware.demo3.dao.AbstractValidator;


@Component(value="doctorValidator")
public class DoctorValidator extends AbstractValidator {

    @Override
    protected void addExtraValidation(Object objectForm, Errors errors) {
        //perform typical validation
        //can autowire to context
    }


}

控制器:(最后是@Valid与验证器的绑定)

@Controller
public class DoctorEditController {

@Autowired
    private DoctorValidator doctorValidator;

@RequestMapping(value = "/doctorEdit", method = RequestMethod.POST)
    public String processSubmit(
            @ModelAttribute("doctorForm") @Valid DoctorForm df,
            BindingResult result,
            ModelMap model) {
     ...
}
@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(doctorValidator);
    }
}

在上下文中声明JSR-303验证器:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

使用此方法,您可以在实际验证器和您要实现的任何其他自定义注释中获取上下文.

标签:java,spring,annotations,bean-validation,hibernate-validator
来源: https://codeday.me/bug/20190630/1337651.html