Springboot 使用自定义注解结合AOP方式校验接口参数

本文介绍了如何在SpringBoot应用中利用自定义注解ParamCheck和AOP进行接口参数校验。首先创建了ParamCheck注解,用于标记需要校验的参数,并设置是否非空和默认值。接着实现了一个名为ParamValidAop的切面,通过AOP的环绕通知来检查带有ParamCheck注解的参数,对非空和默认值情况进行校验。当参数不符合条件时,会抛出自定义异常ParamIsNullException。此外,还提供了一个转换工具类CastValueTypeUtil,用于转换不同类型的参数值。
摘要由CSDN通过智能技术生成

aspectjrt

1.8.9

com.alibaba

fastjson

1.2.58

org.springframework.boot

spring-boot-starter-web

新建自定义注解,ParamCheck.java :

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

/**

  • @Author : JCccc

  • @CreateTime : 2020/5/14

  • @Description :

**/

@Target(ElementType.PARAMETER)

@Retention(RetentionPolicy.RUNTIME)

public @interface ParamCheck {

/**

  • 是否非空,默认不能为空

*/

boolean notNull() default true;

/**

  • 默认值

  • @return

*/

String defaultValue() default “”;

}

简单描述:

ElementType.PARAMETER 使用于参数

boolean notNull() default true; 要求参数不为空,默认开启,可以自己传

String defaultValue() default “”; 默认值,默认设置 “”,可以自己传

接下来新建 参数校验的AOP实现类,ParamValidAop.java:

import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.*;

import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.stereotype.Component;

import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

/**

  • @Author : JCccc

  • @CreateTime : 2020/5/14

  • @Description :

**/

@Component

@Aspect

public class ParamValidAop {

/**

  • 定义有一个切入点,范围为web包下的类

*/

@Pointcut(“execution(public * com.bsapple.vshop.controller….(…))”)

public void checkParam() {

}

@Before(“checkParam()”)

public void doBefore(JoinPoint joinPoint) {

}

/**

  • 检查参数是否为空

*/

@Around(“checkParam()”)

public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

MethodSignature signature = ((MethodSignature) pjp.getSignature());

//得到拦截的方法

Method method = signature.getMethod();

//获取方法参数注解,返回二维数组是因为某些参数可能存在多个注解

Annotation[][] parameterAnnotations = method.getParameterAnnotations();

if (parameterAnnotations == null || parameterAnnotations.length == 0) {

return pjp.proceed();

}

//获取方法参数名

String[] paramNames = signature.getParameterNames();

//获取参数值

Object[] paranValues = pjp.getArgs();

//获取方法参数类型

Class<?>[] parameterTypes = method.getParameterTypes();

for (int i = 0; i < parameterAnnotations.length; i++) {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值