一、引入aop启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
二、 自定义切点注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String value() default "";
}
三、在方法上添加自定义注解(切点)
@LogAnnotation("自定义注解参数")
@GetMapping
public String index(){
// String s = null;
// s.toString();
System.out.println("hello world");
return "hello world";
}
四、编写切面类
package com.hdu.springsecurity.common;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Date;
@Component
@Aspect
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.hdu.springsecurity.common.LogAnnotation)")
public void point(){};
@Before("point()")
public void beforeAdvice(){
log.info("前置通知{}",new Date());
}
@Around("point()")
public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
log.info("环绕前通知{}",new Date());
Object result = joinPoint.proceed();
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
String value = annotation.value();
log.info("注解信息{}",value);
log.info("环绕后通知{}",new Date());
}
@AfterReturning("point()")
public void afterReturningAdvice(){
log.info("后置通知{}",new Date());
}
@After("point()") //finally
public void afterAdvice(){
log.info("最终通知{}",new Date());
}
@AfterThrowing("point()")
public void afterThrowingAdvice(){
log.info("异常通知{}",new Date());
}
}
测试结果(无异常)
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 环绕前通知Mon Apr 17 15:26:15 CST 2023
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 前置通知Mon Apr 17 15:26:15 CST 2023
hello world
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 后置通知Mon Apr 17 15:26:15 CST 2023
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 最终通知Mon Apr 17 15:26:15 CST 2023
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 注解信息自定义注解参数
15:26:15 [main] INFO c.h.springsecurity.common.LogAspect - 环绕后通知Mon Apr 17 15:26:15 CST 2023
测试有异常
15:28:53 [main] INFO c.h.springsecurity.common.LogAspect - 环绕前通知Mon Apr 17 15:28:53 CST 2023
15:28:53 [main] INFO c.h.springsecurity.common.LogAspect - 前置通知Mon Apr 17 15:28:53 CST 2023
15:28:53 [main] INFO c.h.springsecurity.common.LogAspect - 异常通知Mon Apr 17 15:28:53 CST 2023
15:28:53 [main] INFO c.h.springsecurity.common.LogAspect - 最终通知Mon Apr 17 15:28:53 CST 2023
结果:当出现异常:最终通知还是会执行