简体   繁体   English

Spring 注释@Validated 在 kotlin 类中不起作用,相同的 java 代码起作用

[英]Spring annotation @Validated not working in kotlin class, same java code works

I'm have kotlin get request.我有 kotlin get 请求。 Validation are not working, Possible to specify day of week more or less validate limits验证不起作用,可以指定星期几或多或少的验证限制

@RestController
@Validated
open class GetCrab {
    @GetMapping("/v1/get")
open fun getNameOfDayByNumber(@RequestParam dayOfWeek: @Min(1) @Max(7) Int?): String {
        return "ok"
    }
}

In the same java code validation works在同一个java代码验证工作

@RestController
@Validated
public class GetCrab {

    @GetMapping("/v1/get")
    public String getNameOfDayByNumber(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {

        return "ok";
    }
}

Java code when validation works: request:验证工作时的 Java 代码:请求:

http://localhost:12722/v1/get?dayOfWeek=100 http://localhost:12722/v1/get?dayOfWeek=100

Response ->响应 ->

{
"errors": [
    {
        "code": "INTERNAL_SERVER_ERROR",
        "details": "getNameOfDayByNumber.dayOfWeek: must be less than or equal to 7"
    }
]

} }

Kotlin code, request http://localhost:12722/v1/get?dayOfWeek=100 Kotlin 代码,请求http://localhost:12722/v1/get?dayOfWeek=100

Response:回复:

ok

Please use open modifier for methods too.请对方法也使用open修饰符。

Eg please try code:例如,请尝试代码:

@RestController
@Validated
open class GetCrab {
    @GetMapping("/v1/get")
    open fun getNameOfDayByNumber(@RequestParam dayOfWeek: @Min(1) @Max(7) Int?): String {
        return "ok"
    }
}

Both class and method should be open (in Java terms - both of them shouldn't be final), because of Spring proxy logic . 由于 Spring 代理逻辑,类和方法都应该是open (在 Java 术语中 - 它们都不应该是最终的)。 From linked article: Spring tries to inherit your class, because sometimes you can request exact your class from @Autowired parameter.来自链接文章:Spring 尝试继承您的类,因为有时您可以从 @Autowired 参数中请求确切的类。

By default all classes and methods are not final in Java .默认情况下 ,Java 中的所有类和方法 都不是 final 的 However Kotlin classes/methods are final by default , so you need to put open keyword before them to have ability to override.然而,Kotlin 类/方法 默认是 final 的,因此您需要在它们之前放置open关键字才能覆盖。

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

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