如何在spring-boot中创建带有参数的自定义验证器



我为cron字符串编写了一个验证器,用于检查最小间隔。

@Constraint(validatedBy = [ValidMinimalInterval.JsonStringValidator::class])
@Target(AnnotationTarget.FIELD, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class ValidMinimalInterval(
val message: String = "The cron string doesn't fit in the minimal interval of 60 minutes",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
) {
class JsonStringValidator :
ConstraintValidator<ValidMinimalInterval?, String?> {
override fun initialize(jsonString: ValidMinimalInterval?) {}
override fun isValid(string: String?, context: ConstraintValidatorContext): Boolean {
return string?.let {
val min = 1000 * 3600
val cron = CronExpression(string)
val execDate = cron.getNextValidTimeAfter(Date())
val nextExecDate = cron.getNextValidTimeAfter(execDate)
val diff = nextExecDate.time - execDate.time
diff >= min
} ?: true
}
}
}

这很好,但我希望验证器接受最小间隔的参数,如@ValidMinimalInterval(min = 1000 * 3600)。我怎样才能做到这一点?

您只需将其添加为注释属性

annotation class ValidMinimalInterval(
val message: String = "The cron string doesn't fit in the minimal interval of 60 minutes",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
val min: Integer //or whatever it is in Kotlin

)

相关内容

  • 没有找到相关文章

最新更新