Bean 验证仅适用于 Spring 中的控制器方法吗? [英] Bean validation only works for controller methods in Spring?

查看:56
本文介绍了Bean 验证仅适用于 Spring 中的控制器方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用下面的代码,似乎在 Spring 中,bean 验证仅适用于控制器方法(那些使用 @RequestMapping 注释的方法),普通方法不会触发 bean 验证.

Tried with code below, seems in Spring, bean validation only works for controller methods(those who annotated with @RequestMapping), plain methods won't trigger bean validation.

@RequestMapping(value = "/test-validate", method = RequestMethod.POST)
public String test(@Validated Obj obj){
    return "validation-works";
}

@RequestMapping(value = "/test-local-method-validate", method = RequestMethod.POST)
public String test2(@Validated Obj obj){
    Obj obj = new Obj();
    localValidate(obj);//won't validate, though content is null
}

void localValidate(@Validated Obj obj){
    log.debug("entered");
}

//Model
public class Obj{
    @NotNull
    public String content = null;
}

如果我们调用第一个方法:/test-validate,将触发验证,而对于第二个方法:/test-local-method-validate,我们调用一个本地普通方法:localValidate,验证不会工作.

if we call the first method: /test-validate, the validation would trigger, while for the second method: /test-local-method-validate, we call with a local plain method: localValidate, the validation doesn't work.

如果是这样,我如何在普通方法中启用 bean 验证?

If it's true, how can I enable bean validation in plain methods?

推荐答案

答案是:它在您当前的代码中不起作用,因为在调用 localValidate(obj) 时,您正在跳过 Spring 创建的代理完全由这个代理负责验证部分.

The answer is: it will not work in your current code because when calling localValidate(obj) you are skipping the Spring created proxy completely and this proxy is responsible for the validation part.

选项:

  1. 您可以将此逻辑提取到另一个受包保护范围的 Spring 组件,将其注入控制器并调用它而不是您的 localValidate 方法,
  2. org.springframework.validation.Validator 注入您的控制器并手动调用它
  1. You could extract this logic to another, package protected scoped, Spring component, inject it to the controller and call it instead of your localValidate method,
  2. Inject org.springframework.validation.Validator to your controller and call it manually

这篇关于Bean 验证仅适用于 Spring 中的控制器方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆