gpt4 book ai didi

java - hibernate validator 。如何使用@Valid 注解?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:38 25 4
gpt4 key购买 nike

@Valid 注解放在方法参数层的目的是什么?

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

我创建了一个测试,并向该方法传递了一个无效对象,但没有任何反应。
我希望得到一个异常(exception)。

最佳答案

对象上的@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 容器正在处理的请求时,example 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) {
// ...
}
}

在这种情况下,运行该程序将不会触发 Example 参数的验证,即使您包含了所有 JSR 303 运行时 JAR .这是因为没有可用的容器来实现方法级别的验证。 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.

关于java - hibernate validator 。如何使用@Valid 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com