此验证程序检查数据库中登录名的唯一性。在第一次检查时,即当他进入 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>> = [])@Serviceclass 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) }
1 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
我不明白为什么会这样,并决定发布第二次验证。最后,一切正常。为什么spring要验证几次我没看懂,但是我觉得这段代码在实现上还是挺有效的。
class ValidatorUniqueLogin : ConstraintValidator<UniqueLogin, String> {
@Autowired val serviceAccaunt: ServiceAccaunt? = null
override fun initialize(annotation: UniqueLogin?) {}
override fun isValid(login: String, ctx: ConstraintValidatorContext): Boolean {
return if (serviceAccaunt!= null) !(serviceAccaunt.isHaveLogin(login)) else true
}
}
添加回答
举报
0/150
提交
取消