业务场景:在实现业务的过程中,往往都需要写一些繁琐的判断参数是否为null的代码,接口spring-aop 加注解实现通用的处理方法,使代码更为简洁
1.先写好注解类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@Documented
public @interface JParamsCheck {
/**
* 不需要检查参数的下标,例如 String 1 String 2 String 3
* String 1 和String 3 不需要检查 则 NCI = "0,2"
* */
String NCI() default "";
/**
* 需要检测对象里面的参数的值是否为null,被检测的对象必须为标准的javaBean,或Map
* 例如现在有三个参数,Map param1,Map param2,Map param3,
* 需要检测param1 里面Id不能为null
* param2 里面的name和age不能为null
* json串的格式应该 为 {下标:待检测的字符串有多个用‘,’隔开}
* OCF = {0:"id",1:"name,age"}
* 测试git 提交
*
**/
String OCF() default "";
}
上面这个注解,两个参数,包含了两种情况,还有很大的扩展空间,比如限制参数类型之类的!
2.实现切面
@Aspect
@Configuration
public class SystemVerifyAspect {
/**
* 校验参数是否有效
*
* **/
@SuppressWarnings("unused")
@Around(value = "@annotation(com.test.JParamsCheck)")
public Object paramVerify(ProceedingJoinPoint pjp) throws Throwable{
JParamsCheck checkParams =((MethodSignature)pjp.getSignature()).getMethod().getAnnotation(JParamsCheck.class);
String NCI = checkParams.NCI();
String OCF = checkParams.OCF();
JSONObject jsonObj = null;
if(!MyFormat.isStrNull(OCF)) {
jsonObj = JSON.parseObject(OCF);
}
String[] indexs = NCI.split(",");
@SuppressWarnings("rawtypes")
List lists = Arrays.asList(indexs);
boolean flag = true;
Object[] obj = pjp.getArgs();
forObj:for(int i=0;i<obj.length;i++){
if(lists.contains(i+"")){//包含无需检查的下标,跳过检查
continue;
}else{
if(MyFormat.isStrNull(obj[i])){//表示有为null,直接跳出循环
flag = false;
break;
}else if(jsonObj != null &&jsonObj.get(i+"") != null){//表示对象内有需要检测的参数
String[] params = jsonObj.get(i+"").toString().split(",");
//把Obj[i]强行转为jsonObj
JSONObject pObj = JSON.parseObject(JSON.toJSONString(obj[i]));
forParams:for(String k:params) {
if(MyFormat.isStrNull(pObj.get(k))) {//表示其中有参数为null,跳出循环
flag = false;
break forObj;
}
}
}
}
}
if(flag){
try {
return pjp.proceed();
} catch (Exception e) {
e.printStackTrace();
return ResponseObj.returnError("服务器内部异常:"+e.getMessage());
}
}else{
return ResponseObj.returnError("参数异常");
}
}
}
上面我实现了环绕通知,切入点就是这个注解修饰的方法,,我们通过这个获取这个注解的参数,然后通过规则来检测判断参数是否符合标准。这样很轻松的就实现了对方法级别通用的参数校验。
3.使用示例子
@JParamsCheck(OCF="{0:'id'}")
@PostMapping("/type/update")
public ResponseObj typeUpdate(CustomerFileTypeEntity customerFileType) {
return customerFileRepository.typeUpdate(customerFileType);
}
如上所示,我希望第一个参数里面的id不能为null
3108

被折叠的 条评论
为什么被折叠?



