Java @Valid 注释在 Spring 中表示什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3595160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:22:08  来源:igfitidea点击:

What does the @Valid annotation indicate in Spring?

javaspringspring-mvcspring-annotations

提问by Gary Ford

In the following example, the ScriptFileparameter is marked with an @Validannotation.

在以下示例中,ScriptFile参数用@Valid注释标记。

What does @Validannotation do?

是什么@Valid注解吗?

@RequestMapping(value = "/scriptfile", method = RequestMethod.POST)    
public String create(@Valid ScriptFile scriptFile, BindingResult result, ModelMap modelMap) {    
    if (scriptFile == null) throw new IllegalArgumentException("A scriptFile is required");        
    if (result.hasErrors()) {        
        modelMap.addAttribute("scriptFile", scriptFile);            
        modelMap.addAttribute("showcases", ShowCase.findAllShowCases());            
        return "scriptfile/create";            
    }        
    scriptFile.persist();        
    return "redirect:/scriptfile/" + scriptFile.getId();        
}    

采纳答案by mhshams

It's for validation purposes.

它用于验证目的。

Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.

验证 在将用户输入绑定到模型之后验证模型是很常见的。Spring 3 支持使用 JSR-303 进行声明式验证。如果您的类路径中存在 JSR-303 提供程序(例如 Hibernate Validator),则会自动启用此支持。启用后,您可以简单地通过使用@Valid 注解注解Controller 方法参数来触发验证:绑定传入的POST 参数后,将验证AppointmentForm;在这种情况下,要验证日期字段值不为空并且在将来发生。


Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/


在这里查看更多信息:http:
//blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/

回答by Mateusz Dymczyk

IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

IIRC @Valid 不是 Spring 注释而是 JSR-303 注释(这是 Bean 验证标准)。它所做的基本上是检查您发送给该方法的数据是否有效(它将为您验证 scriptFile)。

回答by puneet goyal

Just adding to the above answer, In a web application @validis used where the bean to be validated is also annotated with validation annotations e.g. @NotNull, @Email(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results. bindingResult.hasErrors()will tell if any validation failed.

只是添加到上面的答案中,在 Web 应用程序 @valid中,要验证的 bean 也使用验证注释进行注释,例如@NotNull@Email(休眠注释),因此当从用户获取输入时,可以验证值并且绑定结果将具有验证结果。 bindingResult.hasErrors()将告诉是否任何验证失败。

回答by Charith De Silva

Adding to above answers, take a look at following. AppointmentForm's datecolumn is annotated with couple of annotations. By having @Validannotation that triggers validations on the AppointmentForm(in this case @NotNulland @Future). These annotations could come from different JSR-303 providers (e.g, Hibernate, Spring..etc).

添加到上面的答案,看看下面。AppointmentFormdate列用几个注释进行注释。通过具有@Valid触发验证的注释AppointmentForm(在本例中为@NotNull@Future)。这些注释可能来自不同的 JSR-303 提供者(例如,Hibernate、Spring 等)。

    @RequestMapping(value = "/appointments", method = RequestMethod.POST)
    public String add(@Valid AppointmentForm form, BindingResult result) {
        ....
    }

    static class AppointmentForm {

        @NotNull @Future
        private Date date;
    }

回答by mzlobecki

public String create(@Valid @NotNull ScriptFile scriptFile, BindingResult result, ModelMap modelMap) {    
    if (scriptFile == null) throw new IllegalArgumentException("A scriptFile is required");        

I guess this @NotNullannotation is valid therefore if condition is not needed.

@NotNull如果不需要条件,我想这个注释是有效的。

回答by yuranos

@Validin itself has nothing to do with Spring. It's part of Bean Validation specification(there are several of them, the latest one being JSR 380 as of second half of 2017), but @Validis very old and derives all the way from JSR 303.

@Valid本身与Spring无关。它是 Bean Validation 规范的一部分(其中有几个,最新的一个是 2017 年下半年的 JSR 380),但是@Valid很旧并且一直从 JSR 303 派生。

As we all know, Spring is very good at providing integration with all different JSRs and java libraries in general(think of JPA, JTA, Caching, etc.) and of course those guys took care of validation as well. One of the key components that facilitates this is MethodValidationPostProcessor.

众所周知,Spring 非常擅长提供与所有不同 JSR 和 Java 库的集成(想想 JPA、JTA、缓存等),当然这些人也负责验证。促进这一点的关键组件之一是MethodValidationPostProcessor

Trying to answer your question - @Validis very handy for so called validation cascading when you want to validate a complex graph and not just a top-level elements of an object. Every time you want to go deeper, you have to use @Valid. That's what JSR dictates. Spring will comply with that with some minor deviations(for example I tried putting @Validatedinstead of @Validon RestController method and validation works, but the same will not apply for a regular "service" beans).

尝试回答您的问题 -@Valid当您想要验证复杂图形而不仅仅是对象的顶级元素时,对于所谓的验证级联非常方便。每次想要更深入时,都必须使用@Valid. 这就是 JSR 所规定的。Spring 将遵守一些小的偏差(例如,我尝试将@Validated而不是@Valid放在 RestController 方法和验证工作上,但同样不适用于常规的“服务”bean)。

回答by Sean Gildea

Another handy aspect of @Valid not mentioned above is that (ie: using Postman to test an endpoint) @Valid will format the output of an incorrect REST call into formatted JSON instead of a blob of barely readable text. This is very useful if you are creating a commercially consumable API for your users.

上面没有提到的@Valid 的另一个方便的方面是(即:使用 Postman 测试端点)@Valid 会将不正确的 REST 调用的输出格式化为格式化的 JSON,而不是一团几乎不可读的文本。如果您正在为您的用户创建商业消费 API,这将非常有用。