如何在Spring中以编程方式调用使用@Valid参数在@RequestMethod方法上运行的同一验证器? [英] How can I programmatically call the same validator that runs on a @RequestMethod method with a @Valid parameter in Spring?

查看:560
本文介绍了如何在Spring中以编程方式调用使用@Valid参数在@RequestMethod方法上运行的同一验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在某些字段(例如@NotNull@Size(min = 4, max = 50)等)上带有hibernate验证批注的类

I have a class with hibernate's validation annotation on some fields (such as @NotNull and @Size(min = 4, max = 50), etc...)

public class MyClass {

    Long id;

    @NotEmpty
    @Size(min = 4, max = 50)
    String machineName;

    @NotEmpty
    @Size(min = 4, max = 50)
    String humanName;

    // Getters, setters, etc…
}

我还有一个充当JSON API的自定义控制器,以及一个在调用API方法时创建MyClass对象的JSON解串器.在我的自定义控制器中,我有一个方法可以创建该类型的新对象:

I also have a custom controller that acts as a JSON API, and a JSON deserializer that creates MyClass objects when API methods are called. In my custom controller I have a method to create a new object of that type:

@RequestMapping(method = RequestMethod.POST)
public long createMyObject(@RequestBody @Valid MyClass newObj) {
    // Create the object in the database
    return newObj.getId();
}

和另一种更新现有对象的方法

and another method that updates an existing object

@RequestMapping(method = RequestMethod.PUT)
public void updateMyObject(@RequestBody MyClass updatedObj) {
    MyClass existingObj = // Get existing obj from DB by updatedObj.getId();

    // Do some secondary validation, such as making sure that a specific
    // field remains unchanged compared to the existing instance
    if (existingObj.getMachineName() != null && 
            !existingObj.getMachineName().equals(updatedObj.getMachineName())) {
        throw new CannotChangeMachineNameException();
    }
    else {
        updatedObj.setMachineName(existingObj.getMachineName());
    }

    // [HERE IS WHERE I WANT THE MAGIC TO HAPPEN]

    // Save updatedObj to the database
}

虽然我可以在createMyObject中使用@Valid,但是不能在updateMyObject中使用它,因为我们的API实现要求machineName保持不变-用户可以使用JSON对象调用API,该对象可以完全排除machineName或填充它与数据库中存在的值相同.*

While I can use @Valid in createMyObject, I cannot use it in updateMyObject because our API implementation requires that machineName remains unchanged - users can call the API with a JSON object that either excludes machineName entirely or populate it with the same value that exists in the database.*

在将更新的对象保存到数据库之前,我想调用具有@Valid批注将导致被调用的同一验证器.如何找到并使用此验证器?

Before saving the updated object to the database I want to call the same validator that having the @Valid annotation would cause to be called. How can I find this validator and use it?

推荐答案

没什么说您只需要在控制器方法中使用@Valid即可.为什么不创建一个验证方法,以接受您注释为@Valid的参数,然后仅返回相同的参数.

Nothing says you need to use @Valid in your controller methods only. Why not make a validation method that accepts a parameter you annotate as @Valid, then just return that same parameter.

赞:

public Book validateBook(@Valid Book book) {
   return book;
}

看起来可以选择使用Hibernate的验证包. 这是文档.

Looks like an alternative would be to use Hibernate's validation package. Here's it's documentation.

基本上,您是从ValidationFactory中获得一个Validator,然后像这样使用验证器:

Basically, you get a Validator from a ValidationFactory, and then use the validator like this:

 @Test
    public void manufacturerIsNull() {
        Car car = new Car(null, "DD-AB-123", 4);

        Set<ConstraintViolation<Car>> constraintViolations =
            validator.validate(car);

        assertEquals(1, constraintViolations.size());
        assertEquals("may not be null", constraintViolations.iterator().next().getMessage());
}

这篇关于如何在Spring中以编程方式调用使用@Valid参数在@RequestMethod方法上运行的同一验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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