1.背景
很多時候我們在梳理公共異常時,需要獲取到接口的而具體名稱,便於很好的提示是那個接口錯誤了
2.實現邏輯
1.在controller方法上的注解上寫方法名稱,一般使用了swagger都有方法名稱;
2.使用aop通過JoinPoint,使用反射拿到注解上的方法名稱;
3.把方法名稱放到ThreadLocal里面;
4.在公用異常處理的地方從ThreadLocal里面獲取到方法名稱;
...搞定!
3.具體代碼
1.在controller方法上的注解上寫方法名稱,一般使用了swagger都有方法名稱;
2.使用aop通過JoinPoint,使用反射拿到注解上的方法名稱;
/** * @Description 獲取注解中對方法的描述信息 用於Controller層注解 */ public static String getControllerMethodDescription(JoinPoint joinPoint) throws ClassNotFoundException { String description = ""; String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName();//目標方法名 Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); // 獲取類上的注解 Annotation annotation1 = targetClass.getAnnotation(Api.class); if (annotation1 != null) { String[] tags = ((Api) annotation1).tags(); for (String tag : tags) { description += tag; } } // 獲取方法上的注解 Method[] methods = targetClass.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { ApiOperation annotation = method.getAnnotation(ApiOperation.class); description += annotation == null ? "未命名接口" : annotation.value(); break; } } } return description; }
3.把方法名稱放到ThreadLocal里面;
調用set方法即可
public class ThreadLocalUtil { private static ThreadLocal<String> localVar = new ThreadLocal<>(); public static void set(String name) { localVar.set(name); } public static String get() { String s = localVar.get(); localVar.remove(); return s; } public static void remove() { localVar.remove(); } }
4.在公用異常處理的地方從ThreadLocal里面獲取到方法名稱;
完美!