【问题标题】:Spring Boot method validationSpring Boot 方法验证
【发布时间】:2018-03-10 15:36:16
【问题描述】:

问题

我对@9​​87654321@ 和itemUuid 有以下限制:

  • 两个字符串都不能是null
  • 两个字符串都必须是 UUID(例如f1aecbba-d454-40fd-83d6-a547ff6ff09e)。
  • 组合(userUuid, itemUuid) 必须是唯一的。

我尝试在我的控制器中实现验证,例如:

@RestController
@Validated // (1)
public class CartItemController {

    @PostMapping("/me/carts/{itemUuid}")
    @ResponseStatus(HttpStatus.CREATED)
    public void addItem(@PathVariable("itemUuid") String itemUuid,
                        Authentication auth) {
        CartItemId id = getCartItemId(getUserUuidFrom(auth), itemUuid);
        ...
    }

    @Unique // (4)
    public CartItemId getCartItemId(@NotNull @Uuid String userUuid, // (2)
                                    @NotNull @Uuid String itemUuid) { // (3)
        return new CartItemId(userUuid, itemUuid);
    }
    ...
}

@Uuid@Unique 是自定义约束。在(1) 中启用了方法验证。 (2) 是用户 UUID 的约束。 (3) 是项目 UUID 的约束。唯一约束应用于(4) 中返回的CartItemId。但是,永远不会验证参数和返回值。既不是标准的@NotNull 约束也不是我的自定义约束。我收到的是 HTTP 状态 201 Created 而不是 400 Bad Request

我做错了什么?

有用的东西

以下代码适用于项目 UUID:

@RestController
@Validated
public class CartItemController {

    @PostMapping("/me/{itemUuid}")
    @ResponseStatus(HttpStatus.CREATED)
    public void addItem(@PathVariable("itemUuid") @Uuid String itemUuid, // (1)
                        Authentication auth) {
        ...
    }

}

@Uuid 添加到路径变量参数有效。像anInvalidUuid 这样的值会被拒绝。我还在其他用例中测试了@Unique 约束,它运行良好。

addItem()toId() 有什么区别?

版本

我正在使用 Java 1.8 和 Spring Boot 2.0.0.RELEASEorg.hibernate.validator:hibernate-validator:6.0.7.Final 在我的类路径中。

【问题讨论】:

    标签: java spring spring-boot bean-validation


    【解决方案1】:

    方法参数的验证基于 AOP:验证代理拦截方法调用并在委托(如果一切都有效)之前验证参数,以实际方法。

    您正在从同一类的另一个方法调用getCartItemId() 方法。所以方法调用不会通过代理。只能拦截 bean 间调用。

    所以,简而言之,getCartItemId 应该在一个单独的 bean 中,注入到您的控制器中。

    【讨论】:

    • 谢谢,我将toId() 移到了一个不同的类,并用@Component(使它成为一个bean)和@Validated 进行了注释。它完美地工作。我会尝试找到一个更清洁的解决方案,但您的回答很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 2021-01-30
    • 2021-02-07
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多