学习自定义注解可以从参数判断@ParamJudgement开始

发布时间:2026/8/30 11:53:32
学习自定义注解可以从参数判断@ParamJudgement开始 注解介绍importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/** * 参数空值处理注解 * 1、从第一个对象开始 * 2、给定的参数为顺序判断数量-1 */Retention(RetentionPolicy.RUNTIME)Target(ElementType.METHOD)publicinterfaceParamJudgement{intvalue()default0;}切面类importannotation.ParamJudgement;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.springframework.stereotype.Component;/*** * 功能:处理方法参数空值判断处理 * 优化空间较大 * */ComponentAspectpublicclassParamJudgementAspect{Around(annotation(paramJudgement))publicObjectaround(ProceedingJoinPointjoinPoint,ParamJudgementparamJudgement){Objectobjnull;Object[]argsjoinPoint.getArgs();intvalueparamJudgement.value();StringnamejoinPoint.getSignature().getName();for(inti0;ivalue;i){Objectparamargs[i];if(paramnull){thrownewIllegalArgumentException(name的参数异常不合法);}}try{objjoinPoint.proceed();}catch(Throwablethrowable){//throwable.printStackTrace();thrownewRuntimeException(throwable);}returnobj;}}使用示例注意在spring项目中使用。