Mat*_*nkt 12 spring-mvc bean-validation kotlin
使用Bean Validation 2.0,还可以对容器元素设置约束.
我无法使用Kotlin数据类:
data class Some(val someMap: Map<String, @Length(max = 255) String>)
Run Code Online (Sandbox Code Playgroud)
这没有任何效果.有任何想法吗?
我创建了一个包含示例项目的存储库来重现案例:https://github.com/mduesterhoeft/bean-validation-container-constraints
小智 6
将此配置添加到您的build.gradle(请注意...意味着已经存在的任何内容):
格罗维:
compileKotlin {
kotlinOptions {
freeCompilerArgs = [..., "-Xemit-jvm-type-annotations"]
...
}
}
Run Code Online (Sandbox Code Playgroud)
科特林 DSL:
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf(..., "-Xemit-jvm-type-annotations")
...
}
}
Run Code Online (Sandbox Code Playgroud)
从 Kotlin 1.3.70 和 1.4 开始,应该可以设置特定的编译器选项:https://kotlinlang.org/docs/reference/whatsnew14.html#type-annotations-in-the-jvm-bytecode。
在任何以前的版本或任何这种支持不够的情况下,您必须编写一个自定义验证器。
验证集合仅包含十六进制字符串的示例一:
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.FIELD,
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.VALUE_PARAMETER
)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [HexStringElementsValidator::class])
annotation class HexStringElements(
val message: String = "must only contain hex values",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Any>> = []
)
class HexStringElementsValidator : ConstraintValidator<HexStringElements, Collection<Any>> {
companion object {
val pattern = "^[a-fA-F0-9]+\$".toRegex()
}
override fun isValid(value: Collection<Any>?, context: ConstraintValidatorContext?) =
value == null || value.all { it is String && pattern.matches(it) }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |