三步:
1.引入springboot-boot-start-aop jar包
<!--springboot与aop集成jar包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2.开发切面
两个主要的注解:@Configuration ,让springboot框架做自动配置
@Aspect ,告知springboot这个类是一个切面类
前置通知和后置通知的开发。
@Configuration @Aspect public class MyAspect { //前置通知 @Before("within(com.lkl.service.UserServiceImpl)") public void BeforeSearch(JoinPoint joinPoint){ System.out.println("目标类:"+joinPoint.getTarget()); System.out.println("方法名:"+joinPoint.getSignature().getName()); System.out.println("方法参数:"+joinPoint.getArgs()); System.out.println("=========这是为查询所有开发的前置通知========"); } //后置通知 @After("execution(* com.lkl.service.UserServiceImpl.*(..))") public void AfterTest(JoinPoint joinPoint){ System.out.println("===========后置通知==========="); System.out.println("目标类:"+joinPoint.getTarget()); System.out.println("方法名:"+joinPoint.getSignature().getName()); System.out.println("方法参数:"+joinPoint.getArgs()); } }
前置通知和后置通知类似,了解即可。主要掌握环绕通知
后置通知的开发
@Configuration @Aspect public class MyAspect { @Around("execution(* com.lkl.service.UserServiceImpl.*(..))") public Object aroundTest(ProceedingJoinPoint proceedingJoinPoint){ System.out.println("目标类:"+proceedingJoinPoint.getTarget()); System.out.println("目标方法:"+proceedingJoinPoint.getSignature().getName()); System.out.println("目标方法参数:"+proceedingJoinPoint.getArgs()); System.out.println("==========进入环绕通知之前========="); Object proceed = null; try { proceed = proceedingJoinPoint.proceed(); //放行 System.out.println("目标方法的返回值:"+proceed); System.out.println("========执行目标方法之后的操作========"); return proceed; //将目标方法执行的结果返回 } catch (Throwable throwable) { System.out.println("==========异常通知========="); throwable.printStackTrace(); } return null; } }
3.注意事项
1)前置通知和后置通知,自定义方法传递参数是:JoinPoint
2)环绕通知,传递参数为:ProceedingJoinPoint
原文地址:https://www.cnblogs.com/lkldeblog/p/10627691.html
时间: 2024-10-06 22:26:17