相关注解
@EnableAspectJAutoProxy
@Aspect
@Pointcut
@Before
@After
@Around
@AfterReturning
@AfterThrowing
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
spring声明支持aop
@MapperScan("com.my.learn.mapper")@SpringBootApplication@EnableAspectJAutoProxy //开启spring对注解aop的支持public class MyBatisLearnApplication {public static void main(String[] args) {SpringApplication.run(MyBatisLearnApplication.class);}}
定义切面
@Aspect@Componentpublic class RequestAspectConfig {/*** 在注解中如何使⽤呢?* 第⼀步:编写⼀个⽅法* 第⼆步:在⽅法使⽤@Pointcut注解* 第三步:给注解的value属性提供切⼊点表达式* 细节:* 1.在引⽤切⼊点表达式时,必须是⽅法名+(),例如"pointcut()"。* 2.在当前切⾯中使⽤,可以直接写⽅法名。在其他切⾯中使⽤必须是全限定⽅法名。*/@Pointcut("execution(* com.my.learn.controller.*.*(..))")public void pointcut() {}@Before("pointcut()")public void beforePrintLog(JoinPoint jp) {Object[] args = jp.getArgs();System.out.println("前置通知:beforePrintLog,参数是:" + Arrays.toString(args));}@AfterReturning(value = "pointcut()", returning = "rtValue")public void afterReturningPrintLog(Object rtValue) {System.out.println("后置通知:afterReturningPrintLog,返回值是:" + rtValue);}@AfterThrowing(value = "pointcut()", throwing = "e")public void afterThrowingPrintLog(Throwable e) {System.out.println("异常通知:afterThrowingPrintLog,异常是:" + e);}@After("pointcut()")public void afterPrintLog() {System.out.println("最终通知:afterPrintLog");}/*** 环绕通知* @param pjp* @return*/@Around("pointcut()")public Object aroundPrintLog(ProceedingJoinPoint pjp) {//定义返回值Object rtValue = null;try {//前置通知System.out.println("前置通知");//1.获取参数Object[] args = pjp.getArgs();//2.执⾏切⼊点⽅法rtValue = pjp.proceed(args);//后置通知System.out.println("后置通知");} catch (Throwable t) {//异常通知System.out.println("异常通知");t.printStackTrace();} finally {//最终通知System.out.println("最终通知");}return rtValue;}}
