Spring不会创建ConstraintValidator

时间:2018-04-07 22:38:00

标签: java spring kotlin bean-validation

Spring不会创建实现RolesValidator的类的实例。 即使我用@Configuartion注释@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) } Spring创建它的实例,但验证不起作用。

这是我的代码:

In [41]: df.apply(np.sort, axis=1).groupby(['from','to']).size()
Out[41]:
from  to
a     b     2
c     d     3
dtype: int64

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

2 个答案:

答案 0 :(得分:1)

如果您使用annotation use-site targets,Kotlin测试也会通过:

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

答案 1 :(得分: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 {};
}