前言
仔代碼檢視時,討論到在controller層手動添加日志太麻煩,於是想要注解和切面實現日志的自動輸出,簡化代碼、簡練程序
利用Aspect實現日志切面
1、添加aop依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、定義注解作為切點
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface log { String value() default ""; }
3、聲明切面,完成日志記錄
@Aspect // 使用@Aspect注解聲明一個切面 @Component @Slf4j public class LogAspect { private static final String START = "start"; private static final String END = "end"; @Pointcut("@annotation(com.zh.live.aspect.log)") public void logPointCut() {} @Before("logPointCut()") //前置通知 public void before(JoinPoint point) throws Throwable { try { printLog(point,START); } catch (Exception e) { } } @After("logPointCut()") //后置通知 public void after(JoinPoint point) throws Throwable { try { printLog(point,END); } catch (Exception e) { } } private void printLog(JoinPoint joinPoint, String type) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String beginTime = dateFormat.format(new Date()); //請求的 類名、方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); //請求的參數 Object[] args = joinPoint.getArgs(); //打印日志 log.info("{} {} {} | time: {} param: {} " , className,methodName,type,beginTime,args); } }
4、在controller中需要添加日志的方法上添加@log注解
@log @PostMapping("/registerUser") public R registerUser(@RequestBody UserTo user)
5、postman發送請求進行測試

至此,日志切面就完全結束了,我這里寫的比較簡單,大家也可以任意擴展
