AOP切面编程 后置通知实现返回值的判空值处理(项目中使用)
目的:因为根据平常的代码在service层根据返回值要做判断空值处理,抛对应的错误信息,得每个方法判断一次,比较麻烦。现在的处理方法是根据放回值类型判断是否list.class,是的话list.size()=0抛对应的错误信息,然后在判断是否int.class等,希望能给大家代理帮助。
平常的代码写法
if(i==0){
throw new AppcationException(ExceptionEnum.DELETEDATADEFEAIED);
}
错误类的种类
INSERTDATADEFEATED(1001,"数据插入失败,"),
NOTFOUNTVALUE(1002,"找不到对应的值"),
UPDATEDATADEFEAIED(1003,"更新数据失败"),
DElETEDATADEFEAIED(1004,"更新数据失败");
现在的写法
注意:1.
Class returnType = ((MethodSignature) signature).getReturnType();
Api地址:
http://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/reflect/MethodSignature.html\#getReturnType()
获取返回值类型
2.先判断list.class,int.class然后看是否是get或select开头的。
因为正规的话select开头返回object,get开头返回list,由于大家把两个闹乱了 所以做了一下改造,测试通过。
@Aspect
@Component
public class ExceptionInterceptor {
protected Logger log = (Logger) Logger.getLogger(this.getClass());
/**
* select开头 返回值为object
* get开头 返回值为list
* updat 返回值为int
* delete开头 返回值为int
* insert 返回值为int
*/
@AfterReturning(value = "execution(* com.lenovo.pcsd.bp.businesspartner.mapper.*.*(..))", returning = "result")
@SuppressWarnings("unchecked")
public void afterReturning(JoinPoint joinPoint, Object result) {
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String selectregex = "^select.*$";
String getregex = "^get.*$";
String updateregex = "^updat.*$";
String deleteregex = "^delete.*$";
String insertregex = "^insert.*$";
Class returnType = ((MethodSignature) signature).getReturnType();
Pattern selectp = Pattern.compile(selectregex);
Pattern getp = Pattern.compile(getregex);
Pattern updatp = Pattern.compile(updateregex);
Pattern deletep = Pattern.compile(deleteregex);
Pattern insertp = Pattern.compile(insertregex);
if (returnType.equals(List.class)) {
List<? extends Object> list = (ArrayList<T>) result;
if (list.size() == 0) {
throw new AppcationException(ExceptionEnum.NOTFOUNTVALUE);
}
} else if (returnType.equals(Integer.class)) {
Integer taskList = (Integer) result;
if (taskList == 0) {
if (updatp.matcher(methodName).matches()) {
throw new AppcationException(ExceptionEnum.UPDATEDATADEFEAIED);
} else if (deletep.matcher(methodName).matches()) {
throw new AppcationException(ExceptionEnum.DElETEDATADEFEAIED);
} else if (insertp.matcher(methodName).matches()) {
throw new AppcationException(ExceptionEnum.INSERTDATADEFEATED);
}
}
} else {
if (StringUtils.isEmpty(result)) {
if (getp.matcher(methodName).matches() || selectp.matcher(methodName).matches()) {
throw new AppcationException(ExceptionEnum.NOTFOUNTVALUE);
}
}
}
}
}
还没有评论,来说两句吧...