gpt4 book ai didi

java - 用户定义的验证耦合问题

转载 作者:行者123 更新时间:2023-12-04 05:31:01 24 4
gpt4 key购买 nike

定义了客户端可以使用的 API。客户将通过多种方式连接。其中之一是java-to-java。在这种特定情况下,我遇到了问题。显然,API 应该尽可能地与实现分离。我还没有机会对此进行测试,但是用户定义的验证不会破坏这个模型吗?

我在 API 服务器端实现上通过 Spring @Validated 启用验证。不想将其放入 @Controller 类中,因为这不是进入服务 (API) 的唯一方法。

例如,如果我在接口(interface)中定义了这个方法:

SomeObject updateOperation( AnInputClass param) ...

然后我可以使用 JSR-303 验证进行注释,并且仍然可以解耦:
@NonNull
SomeObject updateOperation(@NonNull AnInputClass 参数) ...
但是,如果我想对输入“参数”的各个部分/部分进行自定义验证,我需要制作自己的注释, 其中有一个 @Constraint(validatedBy) 部分 这部分将与验证实现相关联。它的缩写形式如下:
SomeObject updateOperation ( @CheckInput AnInputClass param)... 
...where the annotation is defined as
...
@Constraint(validatedBy = CheckInputValidator.class) // this is the coupling issue
public @interface CheckInput { ....

由于这一切都发生在服务器端,因此不需要让 Java 客户端拥有这个 CheckInputValidator 类;但是,我没有看到任何选择。首先,我喜欢在 API 中进行验证——它们告诉用户将要验证的内容。如果我可以打破依赖关系并将验证下移到看起来是可以接受的权衡的实现。然而,这会导致下面的异常,所以看起来我被卡住了。任何人都可以帮忙吗?
javax.validation.ConstraintDeclarationException: Only the root method of an 
overridden method in an inheritance hierarchy may be annotated with parameter
constraints, but there are parameter constraints defined at all of the
following overridden methods

最佳答案

我自己找到了答案,我应该早点意识到这一点!

我需要做的就是在接口(interface)/API 层中使用“@Valid”注解。然后,确保用户定义/自定义注释上的@Target 注释定义了“类型”,将@CheckInput 注释应用于所需的类,一切正常!

关于java - 用户定义的验证耦合问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12629558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com