gpt4 book ai didi

java - Spring不创建ConstraintValidator

转载 作者:行者123 更新时间:2023-11-30 06:13:38 26 4
gpt4 key购买 nike

Spring 不会创建实现 ConstraintValidator 的类的实例。即使我使用 @Configuartion 注解 RolesValidator 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)
}

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

最佳答案

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

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

关于java - Spring不创建ConstraintValidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49712645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com