此验证程序检查数据库中登录名的唯一性。在第一次检查时,即当他进入 counterlord 时,一切都很好。但它在保存到数据库时也有效。但不幸的是,负责检查登录唯一性的服务不能@Autowire。问题是什么?是否应该检查 2 次?
class ValidatorUniqueLogin : ConstraintValidator<UniqueLogin, String> {
@Autowired val serviceAccaunt: ServiceAccaunt? = null // this null
override fun initialize(annotation: UniqueLogin?) {}
override fun isValid(login: String, ctx: ConstraintValidatorContext): Boolean {
return serviceAccaunt!!.isHaveLogin(login)
}
}
@Documented
@Constraint(validatedBy = [ValidatorUniqueLogin::class])
@Target(AnnotationTarget.FIELD)
@Retention(RetentionPolicy.RUNTIME)
annotation class UniqueLogin(
val message: String = "{text.error.login.not.unique}",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = []
)
@Service
class ServiceAccaunt(@Autowired val repoAccaunt: RepoAccaunt) {
fun isHaveLogin(login: String): Boolean {
val count = repoAccaunt.countByLogin(login)
return !(count > 0)
}
}
@IsAnonymous
@PostMapping("/reg")
fun reg(
model: Model,
@Valid @ModelAttribute("accaunt") accaunt: Accaunt,
bindingResult: BindingResult
): String {
if (accaunt.roles.isNotEmpty()) {
val acessRoles = serviceRole.findRolesForRegistration()
for (role: Role in accaunt.roles) if (!acessRoles.contains(role)) accaunt.roles.minus(role)
}
喵喵时光机
相关分类