本文共 2656 字,大约阅读时间需要 8 分钟。
平凡也就两个字: 懒和惰;
成功也就两个字: 苦和勤; 优秀也就两个字: 你和我。 跟着我从0学习JAVA、spring全家桶和linux运维等知识,带你从懵懂少年走向人生巅峰,迎娶白富美! 关注微信公众号【 IT特靠谱 】,每一篇文章都是心得总结,跟我学习你就是大牛!
使用AspectJ有两种配置方式:xml配置和java配置。本例以java配置的方式来配置和使用AspectJ。本教程部分截图来源于官方文档!
引入aspectjweaver.jar包依赖,并且jdk版本要求1.8及其以上!
org.aspectj aspectjweaver 1.9.2
在java配置类上添加@EnableAspectJAutoProxy注解来启用AspectJ。
用@Aspect注解定义一个Aspect切面。
package com.test.alltest.aop.config;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;/** * DESC: 自定义切面 * USER: xxx * DATE: 2019/11/12 12:44 * VERSION: 0.0.1 */@Component //指定MyAspect类会被spring自动扫描并注册bean到单例缓存池中@Aspect //表示MyAspect类对象是一个切面对象。可以在切面对象中添加通知、指定切入点等。public class MyAspect {}
通过@Pointcut注解指定切入点。
package com.test.alltest.aop.config;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;/** * DESC: 自定义切面 * USER: xxx * DATE: 2019/11/12 12:44 * VERSION: 0.0.1 */@Component@Aspectpublic class MyAspect { //定义切入点(com.test.alltest.aop.controller包及其子包的所有类的所有方法) @Pointcut("execution(* com.test.alltest.aop.controller..*.*(..))") public void pointCut(){ }}
通过@Before,@After,@Around,@AfterReturning和@AfterThrowing注解分别定义前置通知,后置通知,环绕通知,返回后通知和抛出异常后通知。
package com.test.alltest.aop.config;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;/** * DESC: 自定义切面 * USER: xxx * DATE: 2019/11/12 12:44 * VERSION: 0.0.1 */@Component@Aspectpublic class MyAspect { //定义切入点(com.test.alltest.aop.controller包及其子包的所有类的所有方法) @Pointcut("execution(* com.test.alltest.aop.controller..*.*(..))") public void pointCut(){ } //定义前置通知 @Before("com.test.alltest.aop.config.MyAspect.pointCut()") public void beforeAdvice(){ System.out.println("执行前置通知"); } //定义后置通知 @After("com.test.alltest.aop.config.MyAspect.pointCut()") public void afterAdvice(){ System.out.println("执行后置通知"); } //定义环绕通知 @Around("com.test.alltest.aop.config.MyAspect.pointCut()") public void aroundAdvice(ProceedingJoinPoint joinPoint){ System.out.println("执行环绕通知--开始"); long start = System.currentTimeMillis(); try { joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("耗时:" + (end-start)); System.out.println("执行环绕通知--结束"); } //...方法返回后通知,异常通知同理}
到此为止,AOP面向切面编程你会了吗? 如果以上教程对您有帮助,为了不迷路或需要技术支持,请关注一下吧~
转载地址:http://gupgf.baihongyu.com/