Bean验证API中javax.validation.Payload的用途是什么?

时间:2019-11-24 13:51:41

标签: java-ee bean-validation payload

Bean Validation specification定义:

  

约束注释必须定义一个有效负载元素,该元素指定与约束声明关联的有效负载。有效负载参数的类型为Payload[]

Class<? extends Payload>[] payload() default {};
     

默认值必须为空数组。
  每个可附加的有效负载都扩展Payload

/**
 * Payload type that can be attached to a given
 * constraint declaration.
 * <p/>
 * Payloads are typically used to carry on metadata information
 * consumed by a validation client.
 * </p>
 * Use of payloads is not considered portable.
 */

我已经阅读了其示例,但是例如,我不理解如何在JSF中使用此元数据?您能解释现实世界中有效载荷的其他用例吗?有效负载携带的元数据是什么?

1 个答案:

答案 0 :(得分:1)

也许这个link会帮助你。


import javax.validation.*;
import javax.validation.constraints.NotNull;
import java.util.Set;

public class ConstraintPayloadExample2 {
    private static final Validator validator;

    static {
        Configuration<?> config = Validation.byDefaultProvider().configure();
        ValidatorFactory factory = config.buildValidatorFactory();
        validator = factory.getValidator();
        factory.close();
    }

    public interface AppErrorHandler<T> extends Payload {
        void onError (ConstraintViolation<T> violation);
    }

    public static class ErrorEmailSender<T> implements AppErrorHandler<T> {
        @Override
        public void onError (ConstraintViolation<T> violation) {
            System.out.println("Sending email to support team: " +
                                violation.getPropertyPath() + " " +
                                violation.getMessage());
        }
    }

    public static class TestBean {

        @NotNull(payload = {ErrorEmailSender.class})
        private String str;

        public String getStr () {
            return str;
        }

        public void setStr (String str) {
            this.str = str;
        }
    }

    public static void main (String[] args) {
        TestBean bean = new TestBean();

        Set<ConstraintViolation<TestBean>> constraintViolations =
                            validator.validate(bean);

        if (constraintViolations.size() > 0) {
            constraintViolations.stream().forEach(
                                ConstraintPayloadExample2::processError);
        } else {
            //proceed using user object
            System.out.println(bean);
        }
    }


    private static void processError (ConstraintViolation<TestBean> violation) {
        Set<Class<? extends Payload>> payload =
                            violation.getConstraintDescriptor().getPayload();

        payload.forEach(p -> {
            if (AppErrorHandler.class.isAssignableFrom(p)) {
                try {
                    AppErrorHandler errorHandler = (AppErrorHandler) p.newInstance();
                    errorHandler.onError(violation);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}