JAVA Spring学习笔记------AOP项目
这里只介绍用法
AOP在我看来更像是对代码方法的一次增强
前提是不改动源代码
有一个接口和实现类
接口里边的方法比较简单,只有一个输出
首先我们要导入Maven依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.22</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.8</version> </dependency>
就是这两个依赖
然后我们要创建一个方法增强类
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; //声明为Bean 交给Spring来管理 @Component //声明这是一个Aspect切片 @Aspect public class AopTest { //说明这里是一个切入点 //然后括号里边的字符为 你要增强的方法接口 //原理不太清楚 //实现类的方法也可以 @Pointcut("execution(void com.demo.Dao.Impl.BookDaoImpl.say())") private void pt(){} //这里是说明是在方法调用前还是调用后增强 @Before("pt()") public void test(){ System.out.println(System.currentTimeMillis()); } }
然后我们在Spring配置类中声明一下使用了AOP技术
只需要加入一个注解
@EnableAspectJAutoProxy
如果使用AOP之后造成NoSuchBeanDefinitionException: No qualifying bean of type
那么需要加入一个声明
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Configuration @ComponentScan("com.demo") @Import({JdbcConfig.class, MybatisConfig.class}) //有注解开发的AOP //@EnableAspectJAutoProxy @EnableAspectJAutoProxy(proxyTargetClass = true) public class SpringConfig { }
这样一个基本的方法增强就实现了
测试方法
public class BookTest { @Test public void say(){ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class); BookDao bookDao = applicationContext.getBean(BookDaoImpl.class); bookDao.say(); } }
AOP通知类型
@Around 环绕通知
@Around("gt()") public Object aroundGt(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("Before"); Object ret =proceedingJoinPoint.proceed(); System.out.println("After"); return ret; } @Around("pt()") public void around(ProceedingJoinPoint proceedingJoinPoint){ System.out.println("before"); try { proceedingJoinPoint.proceed(); } catch (Throwable e) { throw new RuntimeException(e); } System.out.println("After"); }
与@Before和@After不同的是
我们需要知道环绕的位置在哪
所以我们要引入ProceedingJoinPoint proceedingJoinPoint
如果我们环绕的方法有返回类型
那么我们需要接受这个返回值,再返回给调用函数
我们可以利用ProceedingJoinPoint proceedingJoinPoint来得到环绕方法的很多信息
可以得到环绕的方法的参数
proceedingJoinPoint.getArgs();
如果要对参数进行修改
那么在修改玩之后应该将修改后的参数发送给proceed()方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!