spring注解版 - aop
/** * AOP * 指 : 在程序运行期间动态的将某段代码切入到指定方法指定位置进行编程的方式 * * 1.导入aop模块:Spring AOP(spring-aspects) * 2、定义一个业务逻辑类 MathCalculator,在业务逻辑运行时将日志进行打印 * 3、定义一个通知 LogAspect,切面中的方法需要动态感知 MathCalculator中的div运行到哪里 * 通知: * 前置通知:logStart : 在目标方法运行之前运行 * 后置通知:logEnd : 在目标方法运行之后运行(无论方法正常结束还是异常结束,都进行调用) * 返回通知:logReturn : 在目标方法正常返回之后运行 * 异常通知 logException : 在目标方法出现异常之后运行 * 环绕通知 动态代理,手动推进目标进行 * 4、给通知的目标方法标注注解 * 5、给通知和 目标对象都加入到容器中 * 6、必须告诉spring,哪一个是通知 (给给通知上加一个注解 @Aspect) * 【7】、给配置类中加上 @EnableAspectJAutoProxy */
1)定义一个业务逻辑类 MathCalculator
/** * @author houChen * @date 2020/7/7 20:08 * @Description: */ public class MathCalculator { public int div(int i,int j){ System.out.println("执行除法!!"); return i/j; } }
2)定义一个通知 LogAspect 并且 给通知的目标方法标注注解
/** * @author houChen * @date 2020/7/7 20:08 * @Description: */ @Aspect public class LogAspect { //抽取公共的切入点表达式 //1 、本类引用 pointCut() //2、 其他类引用 @Pointcut("execution(public int com.atguigu.aop.MathCalculator.*(..))") public void pointCut(){ } //joinPoint一定要出现在参数表的第一位 @Before("pointCut()") public void logStart(JoinPoint joinPoint){ System.out.println(joinPoint.getSignature()+"运行...参数列表是{"+ Arrays.asList(joinPoint.getArgs())+"}"); } @After("pointCut()") public void logEnd(){ System.out.println("除法结束"); } @AfterReturning(value = "pointCut()",returning = "result") public void logReturn(Object result){ System.out.println("除法返回...运行结果{"+result+"}"); } @AfterThrowing(value = "pointCut()",throwing = "exception") public void logException(Exception exception){ System.out.println("除法出现异常{"+exception+"}"); } }
3)给通知和 目标对象都加入到容器中
@Configuration //告诉spring这是一个配置类 public class MainConfigOfAop { @Bean public MathCalculator mathCalculator(){ return new MathCalculator(); } @Bean public LogAspect logAspect(){ return new LogAspect(); } }
4)给配置类中加上 @EnableAspectJAutoProxy
@EnableAspectJAutoProxy @Configuration //告诉spring这是一个配置类 public class MainConfigOfAop { @Bean public MathCalculator mathCalculator(){ return new MathCalculator(); } @Bean public LogAspect logAspect(){ return new LogAspect(); } }
5) 进行测试
public class IocAopTest { //创建ioc容器 ApplicationContext ac =new AnnotationConfigApplicationContext(MainConfigOfAop.class); @Test public void test01(){ MathCalculator mathCalculator = ac.getBean(MathCalculator.class); mathCalculator.div(10, 0); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?