Spring does not create ConstraintValidator Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Spring does not create ConstraintValidator without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Spring does not create an instance of class implementing ConstraintValidator. Even when I annotate RolesValidator with @Configuartion Spring create its instance, but validation doesn’t work.

Here is my code:

@Constraint(validatedBy = [RolesValidator::class])
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class ValidateRoles(
    val message: String = "{com.app.authservice.validators.ValidateRoles.message}",
    val groups: Array<KClass<*>> = arrayOf(),
    val payload: Array<KClass<out Payload>> = arrayOf()
)

//------Validator------

class RolesValidator : ConstraintValidator<ValidateRoles, Collection<String>> {
    lateinit var allowedValues: List<String>

    override fun initialize(constraintAnnotation: ValidateRoles?) {
        allowedValues = RoleType.values().map { it.name }
    }

    override fun isValid(value: Collection<String>?, context: ConstraintValidatorContext?): Boolean {
        return allowedValues.containsAll(value!!)
    }
}

//------Usage------

class AccountUpdateRolesDTO {
    @NotNull
    @ValidateRoles
    var roles: Set<String> = emptySet()
}

//------Controller------

@PreAuthorize("hasAnyAuthority($_ADMIN)")
@Transactional
@PutMapping("/{accountId}/roles")
fun updateRoles(
    @RequestBody @Valid body: AccountUpdateRolesDTO,
    @PathVariable accountId: Long,
    jwt: JWTData
): ResponseEntity<Void> {
    return ResponseEntity(HttpStatus.OK)
}

@edit https://jira.spring.io/browse/SPR-16701

Answer

If you leverage annotation use-site targets, Kotlin tests pass as well:

class KotlinBodyDTO {
    @field:NotNull
    @field:ValidateRolesKotlin
    var roles: Set<String> = emptySet()
}
We are here to answer your question about Spring does not create ConstraintValidator - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji