微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Hibernate Validator.如何使用@Valid注释?

将@Valid注释放在方法参数级别时有什么用途?
public void (@Valid Person p) { ... }

我创建了一个测试,并将此方法传递给非有效对象,但没有任何反应.
我希望得到一个例外.

解决方法

对象上的@Valid注释表示验证框架处理带注释的对象.当在方法的参数上使用时,这被称为方法级验证.请注意,方法级别验证不是核心规范的一部分,实际上只有在将Bean Validation集成到容器类型框架(JSF,CDI,Java EE)中时才支持.当Bean Validation集成到这样的支持容器中时,会发生的是,当在bean上调用生命周期方法时,容器会检测方法参数上的JSR 303注释并触发关联bean的验证.

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

@Path("/example")
public class MyExampleResourceImpl {

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

调用postExample方法以响应JAX-RS容器处理的请求时,将验证示例bean.将此行为与运行独立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) {
        // ...
    }
}

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

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.

原文地址:https://www.jb51.cc/java/126611.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐