aop-获取连接点的信息
实现类代码
package org.atguigu.spring.annotation; import org.springframework.stereotype.Component; @Component public class CalculatorImpl implements Calculator{ @Override public int add(int i, int j) { int result = i + j; System.out.println("内部方法 result = " + result); return result; } @Override public int sub(int i, int j) { int result = i - j; System.out.println("内部方法 result = " + result); return result; } @Override public int mul(int i, int j) { int result = i * j; System.out.println("内部方法 result = " + result); return result; } @Override public int div(int i, int j) { int result = i / j; System.out.println("内部方法 result = " + result); return result; } }
切面代码
package org.atguigu.spring.annotation; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; import java.util.Arrays; @Component @Aspect public class LoggerAspect { @Before("execution(* org.atguigu.spring.annotation.CalculatorImpl.*(..))") public void beforeAdviceMethod(JoinPoint joinPoint){ //获取连接点所对应方法的签名信息 Signature signature = joinPoint.getSignature(); //获取连接点所对应方法的参数 Object[] args = joinPoint.getArgs(); System.out.println("连接点的方法名:"+signature.getName()); System.out.println("连接点方法的参数:"+ Arrays.toString(args)); } @Around("execution(* org.atguigu.spring.annotation.CalculatorImpl.*(..))") public Object aroundAdviceMethod(ProceedingJoinPoint joinPoint) throws Throwable { Object[] args = joinPoint.getArgs(); //将第一个参数x10 args[0] = (int)args[0] * 10; //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args) Object result = joinPoint.proceed(args); System.out.println("环绕通知"); //如果这里不返回result,则目标对象实际返回值会被置为null return result; } }
测试代码
package org.atguigu.spring; import org.atguigu.spring.annotation.Calculator; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestCase { @Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("aop-annotation.xml"); Calculator calculator = context.getBean(Calculator.class); calculator.add(1,2); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律