自定义注解实现参数验证和异常处理

12 篇文章 1 订阅
本文介绍了如何在SpringBoot中使用自定义注解进行参数验证,并设置全局异常处理来捕获验证异常。通过创建自定义注解@IsMobile、实现验证器IsMobileValidator以及定义全局异常处理器GlobalExceptionHandler,实现了登录场景下手机号的格式校验。当验证失败时,返回自定义的错误信息。整个过程展示了SpringBoot应用中优雅地处理参数验证的方法。
摘要由CSDN通过智能技术生成

最近把参数验证修改为自定义注解验证的需求,并设置全局的异常处理来捕捉参数验证未通过的情况。将基本的代码记录一下。

验证情景

简单设置一下情景:
登录情景,登录的用户使用手机号和密码输入进行登录,验证手机号是否符合要求。

依赖信息

引入验证validation依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

参数信息

将输入的手机号和密码整理成一个bean形式,方便使用注解

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginInfo {
    @NotNull
    @IsMobile(required = true)
    private Long phoneNumber;

    @NotNull
    private String password;
}

使用了lombok来减少代码。@NotNull为validation包实现的注解,@IsMobile为自定义注解,用来验证手机号码形式正确性。

自定义注解 @IsMobile

实现自定义注解类,将作用域设置为参数和成员。

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {
    boolean required() default true;
    String message() default "手机格式校验错误";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

require中存放是否必要的布尔值,message中存放错误提示信息,在后续的异常处理中使用。@Constraint注解中对具体的参数验证类进行指定。

验证类 IsMobileValidator

实现ConstraintValidator接口,并在泛型中指定对应的注解类型和验证参数的类型。

// 手机号码校验类
public class IsMobileValidator implements ConstraintValidator<IsMobile, Long> {

    // 是否必要
    private boolean required = false;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(Long s, ConstraintValidatorContext constraintValidatorContext) {
        String ls = s.toString();
        if(required){
            return ValidatorUtil.isMobile(ls);
        }else{
            // 非必要情况,为空也可
            // 不为空则校验
            if(StringUtils.isEmpty(ls)){
                return true;
            }else{
                return ValidatorUtil.isMobile(ls);
            }
        }
    }
}

首先通过initialize()方法可获取到触发验证的注解,进行属性的设置等前置操作。之后调用isValid()方法进行参数验证,返回false的话,会抛出BindException异常。
ValidatorUtil为验证逻辑工具类。

验证逻辑工具类 ValidatorUtil

public class ValidatorUtil {
    public static boolean isMobile(String s){
        if(s.isEmpty())
            return false;
        return s.length() == 11;
    }
}

异常处理类 ExceptionHandler

使用@RestControllerAdvice@ExceptionHandler进行设置。

// 处理控制器抛出的异常
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 所有异常杂糅在一起处理
    @ExceptionHandler(Exception.class)
    public CommonResponse handleException(Exception e){
        System.out.println(e.toString());
        if(e instanceof GlobalException){
            GlobalException ge = (GlobalException)e;
            return new CommonResponse(false, ge.getMESSAGE());
        }else if(e instanceof BindException){
            BindException be = (BindException)e;
            return new CommonResponse(false, "校验异常:" + be.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
        return new CommonResponse(false, e.getMessage());
    }

}

只要是针对BindException进行捕获,使用getBindingResult().getAllErrors().get(0).getDefaultMessage()来获取验证注解中设置的验证错误提示信息,以实现校验错误时的后续处理。

controller中使用

    @ResponseBody
    @RequestMapping("/checkLogin")
    public CommonResponse checkLogin(@Valid LoginInfo loginInfo, HttpServletRequest request, HttpServletResponse response){
        log.info("{}, {}", loginInfo.getPhoneNumber(), loginInfo.getPassword());
        return userService.checkUserLogin(loginInfo.getPhoneNumber(), loginInfo.getPassword(), request, response);
    }

使用@Valid注解即可。

简单演示在这里插入图片描述在这里插入图片描述

总结

使用springboot中集成的hibernate-validator进行参数校验的自定义注解实现,还是挺方便的。简单记录一下用法,感兴趣的看看吧。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
常用的自定义注解有以下几种: 1. @Autowired:用于自动装配依赖对象,可以在Spring容器中自动查找匹配的Bean,并将其注入到目标对象中。 2. @RequestMapping:用于映射HTTP请求的URL路径到具体的处理方法上,可以指定请求的方法、路径、参数等。 3. @Component:用于将一个类标识为Spring容器中的组件,可以通过@ComponentScan注解扫描并注册到容器中。 4. @Transactional:用于标识一个方法或类需要进行事务管理,可以控制事务的提交、回滚等行为。 5. @Validated:用于对方法参数进行校验,可以指定参数验证规则,如非空、长度范围等。 6. @Aspect:用于定义切面,可以在方法执行前、后或异常时执行一些额外的逻辑,如日志记录、性能监控等。 这些是常用的自定义注解,可以根据具体的需求自定义更多的注解来实现特定的功能。 #### 引用[.reference_title] - *1* [Spring Boot中的自定义注解](https://blog.csdn.net/qq_44717657/article/details/130869793)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot项目中自定义注解的使用总结、java自定义注解实战(常用注解DEMO)](https://blog.csdn.net/qq_21187515/article/details/109643130)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [自定义注解](https://blog.csdn.net/u014365523/article/details/126730735)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值