AOP
AOP(Aspect Oriented Programming):动态代理
在程序运行期间将某段代码切入到指定方法指定位置进行运行的编程方式。
通知方法
- 前置通知:在目标方法运行之前运行
- 后置通知:在目标方法结束之后运行
- 返回通知:在目标方法正常返回之后运行
- 异常通知:在目标方法异常返回之后运行
- 环绕通知:动态代理,手动推进目标方法运行
AOP使用
逻辑类
package com.pickle.aop; /** * @author Pickle * @version V1.0 * @date 2024/3/20 17:36 */ public class MathCalculator { public int div(int i, int j){ return i/j; } }
切面类
package com.pickle.aop; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import java.util.Arrays; /** * 切面类 * * @author Pickle * @version V1.0 * @date 2024/3/20 17:47 */ @Slf4j @Aspect public class LogAspects { //抽取公共的切入点表达式 @Pointcut("execution(public * com.pickle.aop.MathCalculator.*(..))") public void pointCut() { } //切入点表达式 @Before("pointCut()") public void logStart(JoinPoint joinPoint) { log.info(joinPoint.getSignature().getName() + "除法运行,参数列表{}", Arrays.asList(joinPoint.getArgs())); } @After("pointCut()") public void logEnd(JoinPoint joinPoint) { log.info(joinPoint.getSignature().getName() +"除法结束"); } @AfterReturning(value = "pointCut()",returning = "result") public void logReturn(Object result) { log.info("除法正常返回,运行结果: {}",result); } @AfterThrowing(value = "pointCut()", throwing = "exception") public void logException(Exception exception) { log.info("除法异常返回,异常信息: {}",exception.getMessage()); } }
加入IOC容器中
package com.pickle.config; import com.pickle.aop.LogAspects; import com.pickle.aop.MathCalculator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * @author Pickle * @version V1.0 * @date 2024/3/20 11:30 */ @Configuration @EnableAspectJAutoProxy public class PickleConfig { //业务逻辑类添加到容器中 @Bean public MathCalculator calculator() { return new MathCalculator(); } // 切面类加入容器中 @Bean public LogAspects logAspects() { return new LogAspects(); } }
测试
@Test void contextLoads() { final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PickleConfig.class); log.info("容器创建完成"); final MathCalculator calculator = (MathCalculator)context.getBean(MathCalculator.class); calculator.div(1,1); System.out.println(calculator); }
结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架