[英]Micronaut custom validation Annotation does not work
I was trying to write a custom annotation to validate a field in a Micronaut project, I came across this section in their documentation Defining Additional Constraints我试图编写一个自定义注释来验证 Micronaut 项目中的一个字段,我在他们的文档Defining Additional Constraints中看到了这一部分
My understanding was that is completely possible to write my own annotation to validate a field in my POJO but after trying for hours, I can't get my validation to work, it simply does not get invoked, could it be I'm missing something fundamental about the way how Micronaut works?我的理解是完全有可能编写我自己的注释来验证我的 POJO 中的字段但是在尝试了几个小时之后,我无法让我的验证工作,它根本没有被调用,可能是我遗漏了什么Micronaut 工作方式的基础知识?
Annotation注解
@Retention(RUNTIME)
@Constraint(validatedBy = [])
annotation class FieldValidator(
val message: String = "invalid format ({validatedValue})"
)
Factory工厂
@Factory
class ValidatorFactory {
@Singleton
fun fieldPatternValidator(): ConstraintValidator<FieldValidator, CharSequence> {
return ConstraintValidator { value, annotation, context ->
context.messageTemplate("invalid format ({validatedValue}), should be test")
value == "test"
}
}
}
Filter筛选
@Introspected
data class HelloWorldFilter(
@FieldValidator
val field: String?
)
Controller控制器
@Controller("/hello")
open class HelloController() {
@Get("{?filters*}")
@Produces(MediaType.TEXT_PLAIN)
open fun index(@Valid filters: HelloWorldFilter): String {
return filters.toString()
}
}
I have a small demo on Github , to reproduce我在Github上有一个小演示,可以重现
run ./gradlew run
运行./gradlew run
call http://localhost:8080/hello?field=abc
that expected behaviour should be bad request since the field is matching the desired value.调用http://localhost:8080/hello?field=abc
预期的行为应该是错误的请求,因为该字段与所需的值匹配。
Using your demo project, I changed your HelloWorldFilter
class to使用您的演示项目,我将您的HelloWorldFilter
类更改为
@Introspected
data class HelloWorldFilter(
@field:FieldValidator
val field: String?
)
Ran it, then:运行它,然后:
curl "http://localhost:8080/hello?field=abc"
Output was as you expect:输出如你所料:
{"message":"Bad Request","_embedded":{"errors":[{"message":"filters.field: invalid format (abc), should be test"}]},"_links":{"self":{"href":"/hello?field=abc","templated":false}}}
With:和:
curl "http://localhost:8080/hello?field=test"
Output:输出:
HelloWorldFilter(field=test)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.