如何修复 Spring Boot 中的错误自定义注解?

我使用 spring boot 2.1.0.BUILD-SNAPSHOT。我创建了一个自定义注释:


@Target({ElementType.TYPE, ElementType.FIELD})

@Retention(RetentionPolicy.RUNTIME)

@Constraint(validatedBy = UniqueUserNameValidator.class)

@Documented

public @interface UniqueUserName {


    String message() default "{truyenmvc.uName.UniqueUserName.message}";


    Class<?>[] groups() default {};


    Class<? extends Payload>[] payload() default {};

}

和验证:


public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName, String> {


    private final UserService userServicel;


    @Autowired

    public UniqueUserNameValidator(UserService userServicel) {

        this.userServicel = userServicel;

    }


    @Override

    public void initialize(UniqueUserName constraintAnnotation) {


    }


    @Override

    public boolean isValid(String userName, ConstraintValidatorContext constraintValidatorContext) {

        return userName != null && !userServicel.checkUserNameExits(userName);

    }

}

在实体


@Entity

@Table(schema = "", uniqueConstraints = {@UniqueConstraint(columnNames = {"uEmail"}),

        @UniqueConstraint(columnNames = {"uDname"}), @UniqueConstraint(columnNames = {"uName"})})

@Data

@NoArgsConstructor

public class User implements Serializable {


    private static final long serialVersionUID = 1L;

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "uID", unique = true, nullable = false)

    private Long uID;

    @NotEmpty(message = "{truyenmvc.uName.empty.message}")

    @UniqueUserName

    @Column(name = "uName", unique = true, nullable = false, length = 30)

    private String uName;

}

谁能告诉我错误在哪里。以及如何克服它?谢谢!


DIEA
浏览 153回答 2
2回答

心有法竹

我认为您应该使用@RestControllerAdvice注释,因为违反约束是一个例外。我认为通过异常处理这个比使用自定义验证器更有效。您可以为您的特定业务逻辑使用验证器。例如:public class ConstraintViolationException extends BaseApiRuntimeException {&nbsp; private static final long serialVersionUID = 1L;&nbsp; public ConstraintViolationException([module eg. enum of project modules] module, String resource) {&nbsp; &nbsp; super(module, resource);&nbsp; }}BaseApiRuntimeException 仅扩展 RuntimeException。包装它将使您更灵活地自定义异常消息。使用控制器建议构建异常处理程序:@RestControllerAdvicepublic class CommonExceptionHandler {&nbsp; @ExceptionHandler(ConstraintViolationException.class)&nbsp; public ResponseEntity<ErrorDetail> handleConstraintViolationException(&nbsp; &nbsp; &nbsp; HttpServletRequest request, ConstraintViolationException base) {&nbsp; &nbsp; LOG.info("CONSTRAINT VIOLATION EXCEPTION: ", base);&nbsp; &nbsp; ErrorDetail error = new ErrorDetail<ConstraintViolationException>().setErrorDetails(&nbsp; &nbsp; &nbsp; &nbsp; CONSTRAINT_VIOLATION, base, "CONSTRAINT VIOLATION USERNAME ALREADY EXIST.");&nbsp; &nbsp; return new ResponseEntity<ErrorDetail>(error, HttpStatus.UNPROCESSABLE_ENTITY);&nbsp; }}您可以在此处创建自己的包装器以生成自定义响应。在这个例子中是 ErrorDetail 类。搜索RestControllerAdvice以获取更多详细信息。您还可以针对您的特定用例将 basePackages 添加到此注释中。编辑:服务层你可以这样使用:throw new ConstraintViolationException([module package e.g enum or string],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "any custom message here: " + anything);

隔江千里

我更改了 UniqueUserNameValidator 类:public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName, String> {@Autowiredprivate UserService userServicel;private String message;@Overridepublic void initialize(UniqueUserName constraintAnnotation) {&nbsp; &nbsp; message = constraintAnnotation.message();}@Overridepublic boolean isValid(String userName, ConstraintValidatorContext constraintValidatorContext) {&nbsp; &nbsp; boolean valid = true;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; valid = userName != null && !userServicel.checkUserNameExits(userName);&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; }&nbsp; &nbsp; if (!valid) {&nbsp; &nbsp; &nbsp; &nbsp; constraintValidatorContext.buildConstraintViolationWithTemplate(message)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .addConstraintViolation()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .disableDefaultConstraintViolation();&nbsp; &nbsp; }&nbsp; &nbsp; return valid;}}这没有错误。谢谢大家帮助我!!!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java