java接口定义统一的异常处理,aop
获取完整的方法名,包含包名、类名、方法名
joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName()
aop中获取请求对象
RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest();
环绕通知获取方法入参的方法
Object[] args = joinPoint.getArgs();
指定拦截带有注解的写法
@Pointcut("@annotation(com.springboot_aop.abc)") public void homeWorkPointcut() { System.out.println(); }
Object[] args = joinPoint.getArgs();//获取所有参数
MethodSignature sign = (MethodSignature) joinPoint.getSignature(); Method method = sign.getMethod();//获取当前方法 MQ annotation = method.getAnnotation(MQ.class);//获取是否有注解 if(annotation!=null){ } for (int k = 0; k < args.length; k++) { Object arg = args[k]; // 获取对象类型 String typeName = arg.getClass().getTypeName(); System.out.println(typeName); }
如果获取不到注解 ,则需要将你的注解定义成运行时保存
@Retention(RetentionPolicy.RUNTIME) public @interface MQ { String a() default ""; }
还有一种简单的方式获取注解,
@Around("testMQ() && @annotation(mq)") public Object deAround(ProceedingJoinPoint joinPoint,MQ mq) throws Throwable {}
获取url里面的参数,获取url后面的参数
RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String queryString = request.getQueryString(); if(StringUtils.isEmpty(queryString)|| !queryString.contains("token")){ throw new RuntimeException("接口调用验证不通过"); } queryString = queryString.substring(queryString.indexOf("token=")+6); if(queryString.contains("&")){ queryString=queryString.substring(0,queryString.indexOf("&")); } log.info("token------------------------"+queryString); Object o = redisTemplate.opsForValue().get(APP_PREFIX+queryString); log.info("token()认证—==="+JSON.toJSONString(o)); if(o==null){ throw new RuntimeException("用户未登录"); }
统一异常处理,aop
@Pointcut("execution(public * com.lyh.prom.modules.web.*.*(..))")限制定义公共方法
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; @Aspect @Component public class TestAop { /** * 定义切入点 */ @Pointcut("execution(* com.springboot_aop.controller.*.*(..))") public void homeWorkPointcut() { System.out.println(); } @Before("homeWorkPointcut()") public void test01() { System.out.println("执行前///////"); } @After("homeWorkPointcut()") public void test02() { System.out.println("执行后////"); } @Around("homeWorkPointcut()") public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("环绕前/////"); try { return joinPoint.proceed(); }catch (Throwable e){ Map<String, Object> data = new HashMap<>(); data.put("code","500"); data.put("msg",e.getMessage()); e.printStackTrace(); return data;
} } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>