简体   繁体   中英

How to create custom validator with parameters in spring boot?

I have written a validator for cron string that checks for a minimal interval.

@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
        }
    }
}

This works fine, but I want the validator to take in the parameter for minimal interval like @ValidMinimalInterval(min = 1000 * 3600) . How can I achieve that?

You just add it as an annotation property

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
    
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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