- 学习Spring中的Aop思想:将公共业务(日志、安全等)和领域业务结合起来,当执行领域业务时会把公共业务加进来,实现公共业务的重复利用。其本质还是动态代理(代理某一类业务)。
- 实现Aop的三种方式
- 通过spring的ApI实现:需要用到两个方法,前置增强需要实现MethodBeforeAdvice接口的方法 。后置增强需要实现AfterReturningAdvice 接口的方法,具体实现代码情况如下:
//前置增强 public class Log implements MethodBeforeAdvice { //method : 要执行的目标对象的方法 //objects : 被调用的方法的参数 //Object : 目标对象 @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了"); } } //后置增强 public class AfterLog implements AfterReturningAdvice { //returnValue 返回值 //method被调用的方法 //args 被调用的方法的对象的参数 //target 被调用的目标对象 @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("执行了" + target.getClass().getName() +"的"+method.getName()+"方法," +"返回值:"+returnValue); } }
- 自定义类来实现ApI:需要使用Aop标签来进行配置,具体配置情况如下:
<bean id="diy" class="com.deng.pojo.DiyPointCut"/> //DiyPointCut是自定义的类 <aop:config> <aop:aspect ref="diy"> <aop:pointcut id="diyPointCut" expression="execution(* com.deng.service.UserServiceImpl.*(..))"/> <aop:after method="after" pointcut-ref="diyPointCut"/> //在方法执行前打印 <aop:before method="before" pointcut-ref="diyPointCut"/> //方法执行后打印 </aop:aspect> </aop:config>
- 通过注解实现Aop:其中需要在bean中开启注解支持
<aop:aspectj-autoproxy/>
具体注解代码实现情况如下
1 package com.deng.annotation; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.After; 5 import org.aspectj.lang.annotation.Around; 6 import org.aspectj.lang.annotation.Aspect; 7 import org.aspectj.lang.annotation.Before; 8 9 @Aspect //标注这个类是一个切面 10 public class AnnotationPointCut { 11 12 @Before("execution(* com.deng.service.UserServiceImpl.*(..))") //在执行UserServiceImpl这个类的方法之前才实现 13 public void Before() 14 { 15 System.out.println("方法执行前"); 16 } 17 18 @After("execution(* com.deng.service.UserServiceImpl.*(..))") //在执行UserServiceImpl这个类的方法之后才实现 19 public void After(){ 20 System.out.println("方法执行后"); 21 } 22 23 @Around(("execution(* com.deng.service.UserServiceImpl.*(..))")) //在执行UserServiceImpl这个过程中实现 24 public void around(ProceedingJoinPoint jp) throws Throwable { 25 System.out.println("环绕前"); 26 Object proceed = jp.proceed(); 27 28 System.out.println("环绕后"); 29 } 30 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!