有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate验证程序。如何使用@Valid注释?

当把@Valid注释放在方法参数级别时,它的用途是什么

public void (@Valid Person p) { ... }

我创建了一个测试,并将无效对象传递给该方法,但什么也没发生
我希望得到一个例外


共 (2) 个答案

  1. # 2 楼答案

    对象上的@Valid注释是验证框架处理注释对象的指示。当用于方法的参数时,这被称为方法级验证。请注意,方法级验证不是核心规范的一部分,事实上,只有当Bean验证集成到容器类型框架(JSF、CDI、JavaEE)中时,才支持方法级验证。当Bean验证集成到这样一个支持容器中时,发生的事情是,在Bean上调用生命周期方法时,容器会检测方法参数上的JSR 303注释,并触发相关Bean的验证

    例如,如果在JAX-RS资源类中有以下方法定义:

    @Path("/example")
    public class MyExampleResourceImpl {
    
        @POST
        @Path("/")
        public Response postExample(@Valid final Example example) {
            // ....
        }
    }
    

    当调用postExample方法以响应JAX-RS容器处理的请求时,将验证examplebean。将此行为与运行独立Java SE应用程序时发生的情况进行对比:

    public class MyMainClass {
        public static void main(final String[] args) {
            final MyMainClass clazz = new MyMainClass();
            clazz.echo(new Example());
        }
    
        public Example echo(@Valid final Example example) {
            // ...
        }
    }
    

    在这种情况下,即使包含了所有JSR303运行时JAR,运行该程序也不会触发Example参数的验证。这是因为没有实现方法级验证的容器可用。附录C中的Bean Validation Specification详细描述了所有这些。为了您的利益,我在下面引用了其中的一些内容:

    Proposal for method-level validation

    This proposition has not been integrated into the core specification and is not part of it. It remains here for archaeological purposes and will be seriously considered for a future revision of this specification. This proposal is likely to be a bit out of sync with the rest of the specification artifacts.

    Note: Bean Validation providers are free to implement this proposal as a specific extension. Such specific extension could for example be accessed via the use of the Validator.unwrap method.

    A popular demand was to provide a method and parameter level validation mechanism reusing the constraint descriptions of the specification. This set of APIs is meant to be used by interceptor frameworks such as:

    • application frameworks like
      • JSR-299
    • component frameworks like Enterprise Java Beans
    • aspect based frameworks

    These frameworks can call the validation APIs to validate either the parameter list or the returned value of a method when such method is called. More precisely, validation occurs around a method invocation. This extension of the Bean Validation API allows to reuse the core engine as well as the constraint definition and declaration for such method level validations.