方式一,实现MethodBeforeAdvice,AfterReturningAdvice接口,在applicationContext.xml中注入bean,创建切入点,配置环绕增加,xml需要引入aop约束。
public void before(Method method, Object[] objects, Object o)//目标方法,方法参数,目标类
public void afterReturning(Object o, Method method, Object[] objects, Object o1)//目标方法返回值,目标方法,方法参数,目标类
1 2 3 4 5 6 7 8 | <aop:config> <!-- 切入点 execution(返回类型 类.方法名(参数列表))--> <!--第一个*代表所有类型,第二个*代表类中所有方法,(..)代表任意参数--> <aop:pointcut id= "pointcut" expression= "execution(* com.jay.service.UserServiceImpl.*(..))" /> <!--执行环绕增加--> <aop:advisor advice- ref = "logBefore" pointcut- ref = "pointcut" ></aop:advisor> <aop:advisor advice- ref = "logAfter" pointcut- ref = "pointcut" ></aop:advisor> </aop:config> |
方式二,自定义类和方法,方法中无法通过参数自动获取目标类的相关信息
1 2 3 4 5 6 7 | <aop:config> <aop:aspect ref = "log" > <aop:pointcut id= "point" expression= "execution(* com.jay.service.UserService.*(..))" /> <aop:before method= "before" pointcut- ref = "point" /> <aop:after method= "after" pointcut- ref = "point" /> </aop:aspect> </aop:config> |
方式三,注解实现AOP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.jay.service; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class AnnotationPointCut { @Before( "execution(* com.jay.service.UserServiceImpl.*(..))" ) public void before(){ System. out .println( "前..." ); } @After( "execution(* com.jay.service.UserServiceImpl.*(..))" ) public void after(){ System. out .println( "后..." ); } } |
配置:
1 2 3 4 | <!--方式三,注解实现AOP--> <bean id= "annotationPointCut" class = "com.jay.service.AnnotationPointCut" /> <!--开启注解支持--> <aop:aspectj-autoproxy/> |
测试:
1 2 3 4 5 6 7 | @Test public void test3() { ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); //代理的是一类业务,需要使用接口 UserService m = context.getBean( "userService" ,UserService. class ); m.getUser( "jay.x" ); } |
要引入依赖
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2015-07-30 WCF、Net remoting、Web service概念及区别
2015-07-30 select into tb_temp2 from tb_temp1 创建临时表实现上一个、下一个功能,使用完毕就删除临时表