AspectJ使用
给下面这个方法增强功能
import org.springframework.stereotype.Component; /** * @Classname: AopTest * @Description: * @Author: Stonffe * @Date: 2023/3/30 20:19 */ @Component public class AopTest { public void func() { System.out.println("function..."); } }
切面
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * @Classname: AopProxy * @Description: * @Author: Stonffe * @Date: 2023/3/30 20:29 */ @Aspect @Component public class AopAspect { @Before("execution(public * com.sora.aop.AopTest.func(..))") public void before() { System.out.println("before..."); } @AfterReturning("execution(public * com.sora.aop.AopTest.func(..))") public void afterReturning() { System.out.println("afterReturning.."); } @After("execution(public * com.sora.aop.AopTest.func(..))") public void after() { System.out.println("after.."); } @Around("execution(public * com.sora.aop.AopTest.func(..))") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { System.out.println("before around.."); Object retVal = pjp.proceed(); System.out.println("after around.."); return retVal; } }
配置Aspectj
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * @Classname: AopConfig * @Description: * @Author: Stonffe * @Date: 2023/3/30 20:21 */ @Configuration @EnableAspectJAutoProxy @ComponentScan(basePackages = {"com.sora.aop"}) public class AopConfig { }
结果
public class Aoptest { @Test public void testAop() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); AopTest bean = context.getBean(AopTest.class); bean.func(); } }
before around.. before... function... after around.. after.. afterReturning..
本文作者:xiaoovo
本文链接:https://www.cnblogs.com/xiaoovo/p/17274317.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步