简体   繁体   English

@Valid bean 验证

[英]@Valid bean validation

Consider the two frameworks shown below.考虑下面显示的两个框架。 Here I need to validate the bean这里我需要验证bean

Controller Controller

In controller I m using @Valid and does the java validation.在 controller 我使用 @Valid 并进行 java 验证。 Works fine工作正常

@RequestMapping("")
void testIt(@Valid @RequestBody User user){

} 

Normal Spring application without controller没有 controller 的普通 Spring 应用

Is there any way to do validation here.有什么方法可以在这里进行验证。 Its not a controller and @Valid doesn't work here.它不是 controller 和 @Valid 在这里不起作用。 Anyways to use @Valid or any similar type of validation for normal function?无论如何要对正常的 function 使用 @Valid 或任何类似类型的验证?

void testIt(@Valid User user){
}

You can enable method validation by declaring beans of type org.springframework.validation.beanvalidation.MethodValidationPostProcessor and org.springframework.validation.beanvalidation.LocalValidatorFactoryBean and annotating the class containing testIt() with the @Validated annotation.您可以通过声明 org.springframework.validation.beanvalidation.MethodValidationPostProcessor 和 org.springframework.validation.beanvalidation.LocalValidatorFactoryBean 类型的 bean 并使用 @Validated 注释注释包含 testIt() 的 class 来启用方法验证。

@Validated
@Component
public class TestIt {
  public void testIt(@Valid User user) {
  ...
  }
}

ConstraintViolationException will be thrown if validation errors occur when calling testIt().如果调用 testIt() 时发生验证错误,将抛出 ConstraintViolationException。 Also, make sure you have Hibernate Validator in your classpath.此外,请确保您的类路径中有 Hibernate 验证器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM