springboot @Aspect 切面接口

约定不等于承诺〃 2022-11-07 05:51 257阅读 0赞

好久没写文章了 更新一个小技术点关于@Aspect 切面接口的应用,不多说上代码

  1. @Slf4j
  2. @Aspect
  3. @Component
  4. public class InterceptorAspect {
  5. @Pointcut("execution(public * com.www.baidu.job..*.*(..))")
  6. public void Pointcut() {
  7. }//签名
  8. @Before(value = "Pointcut()")
  9. public void logBeforeController(JoinPoint joinPoint) {
  10. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//这个RequestContextHolder是Springmvc提供来获得请求的东西
  11. HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
  12. // 记录下请求内容
  13. log.info("已经进入Aspect---Before----- : ", StringUtils.join(joinPoint.getArgs(), ";"));
  14. }
  15. @AfterReturning(value = "Pointcut()", returning = "rvt")
  16. public void after(JoinPoint joinPoint, Object rvt) {
  17. log.info("已经进入Aspect--after----- : ");
  18. //获取类型参数,获取注解中的参数
  19. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  20. Method method = signature.getMethod();
  21. InserVolumeAspect action = method.getAnnotation(InserVolumeAspect.class);
  22. log.info("类型:" + action.type());//通过反射获得注解上的属性 然后做相关操作
  23. //下面就是获取该接口的返回参数
  24. MethodSignature sig1 = (MethodSignature) joinPoint.getSignature();
  25. Method method1 = sig1.getMethod();
  26. if (null != rvt && null != method1.getDeclaringClass()) {
  27. try {
  28. log.info("{} . {} : 返回数据:{}", method1.getDeclaringClass().getName(), method1.getName(), new Gson().toJson(rvt));
  29. } catch (Exception e) {
  30. }
  31. }
  32. }
  33. }

这就是关于aop切面的应用,也可以做系统接口的日志,里边参数的意思百度下都有 简单说下 after函数是方法接口执行完在执行的函数 before是进入方法先执行,比如做成切面的日志接口就可以使用before函数

最后提醒应用者重要的一点 这个自定义注解可以不标注在controller上 但是 AfterReturning返回的参数依然使你controller的返回值

发表评论

表情:
评论列表 (有 0 条评论,257人围观)

还没有评论,来说两句吧...

相关阅读