Spring 不创建 ConstraintValidator

问题描述 投票:0回答:2

Spring 不会创建实现

ConstraintValidator
的类的实例。 即使我用
RolesValidator
注释
@Configuartion
Spring 创建其实例,但验证不起作用。

这是我的代码:

@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://github.com/spring-projects/spring-framework/issues/21242(以前的SPR-16701)

java spring kotlin bean-validation
2个回答
1
投票

如果您利用注释使用站点目标,Kotlin 测试也会通过:

class KotlinBodyDTO {
    @field:NotNull
    @field:ValidateRolesKotlin
    var roles: Set<String> = emptySet()
}

0
投票

Spring 似乎不识别 Kotlin 中的注释。当我将注释转换为 Java 后,一切正常。

@Constraint(validatedBy = RolesValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ValidateRoles {
    String message() default "{com.app.authservice.validators.ValidateRoles.message}";

    Class[] groups() default {};

    Class[] payload() default {};
}
© www.soinside.com 2019 - 2024. All rights reserved.