spring-aop 的 基础使用(啥是增强类、切点、切面)- 2

spring-aop 的 基础使用(啥是增强类、切点、切面) 的基础上,

这里讲如何,在 增强类 的方法中,获取 目标方法 的一些信息

目录结构,

新增加了一个 MyAdvice类

新增加一个 MyAdvice类

java 复制代码
package com.english.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Modifier;

/**
 * 在 增强类 的方法中,获取,目标方法的信息
 *
 * 1、获取,目标方法的方法名、参数、访问修饰符、所属的类信息
 *      在 增强方法 添加 JoinPoint joinPoint 参数,
 *      JoinPoint 就包含了目标方法的信息
 *
 * 2、获取,目标方法的返回结果
 *      只有 @AfterReturning 能获取 目标方法 的返回结果
 *      @AfterReturning(value = "execution(* com..impl.*.*(..))", returning = "myret")
 *      public void afterReturning(JoinPoint joinPoint, Object myret)
 * 
 * 3、获取,目标方法的异常信息
 *      @AfterThrowing(value = "execution(* com..impl.*.*(..))", throwing = "mythrowable")
 *      public void afterThrowing(JoinPoint joinPoint, Throwable mythrowable)
 *
 */
@Aspect
@Component
public class MyAdvice {

    @Before("execution(* com..impl.*.*(..))")
    public void before(JoinPoint joinPoint) {
        // 获取方法属于的类的信息
        String simpleName = joinPoint.getTarget().getClass().getSimpleName();
        System.out.println("simpleName=" + simpleName);

        // 获取访问修饰符
        int modifiers = joinPoint.getSignature().getModifiers(); // int类型
        String s = Modifier.toString(modifiers); // 将 int 转换为 对应的字符串

        // 获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println("name= " + name);

        // 获取目标方法的参数
        Object[] args = joinPoint.getArgs();
    }

    @AfterReturning(value = "execution(* com..impl.*.*(..))", returning = "ret")
    public void afterReturning(JoinPoint joinPoint, Object ret) {
    }

    @AfterThrowing(value = "execution(* com..impl.*.*(..))", throwing = "throwable")
    public void afterThrowing(JoinPoint joinPoint, Throwable throwable) {
    }

    @After("execution(* com..impl.*.*(..))")
    public void after(JoinPoint joinPoint) {
        System.out.println("after");
    }
}
相关推荐
Halo_tjn11 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色11 小时前
java 利用redis来限制用户频繁点击
java·开发语言
PH = 713 小时前
OverlayFS联合文件系统使用示例
java·linux·服务器
AC赳赳老秦13 小时前
OpenClaw进阶技巧:批量修改文件内容、替换关键词,解放双手
java·linux·人工智能·python·算法·测试用例·openclaw
Java小白笔记13 小时前
OpenClaw 实战方法论
java·开发语言·人工智能·ai·全文检索·ai编程·ai写作
呱牛do it14 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 5)
java·vue
练习时长一年14 小时前
Spring配置类的演化
java·spring boot·spring
喜欢流萤吖~14 小时前
服务间的依赖管理:微服务的协作之道
java·微服务
invicinble14 小时前
Spring如何把bean注册到容器里
java·后端·spring
代码不加糖14 小时前
0基础搭建前后端分离项目:实现菜单与界面左右布局
java·前端·javascript·mysql·elementui·mybatis