自定义注解+面向切面 日志记录

自定义注解

package com.example.spring.controller;

import java.lang.annotation.*;

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogTest {
  String type() default "";
  String name() default "";
}

target选择注解可以放在类或者方法上面

retention 什么时候启动注解

切面

@Pointcut 切点,切面什么时候可以切入(切入什么方法)

@Around 环绕加强,有助于对操作前后都操作,必须加上process方法,否则业务代码无法运行

@After 业务跑完之后运行

@AfterThrow 跑完如果抛异常会运行

@AfterReturning(若目标方法无异常,执行@AfterReturning注解方法的业务逻辑)

简单实现

package com.example.spring.controller;

import jdk.nashorn.internal.runtime.logging.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Logger
public class AopTest {

  @Pointcut("@annotation(com.example.spring.controller.LogTest)")
  public void log(){}

  @Around("log()")
  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
      MethodSignature signature = (MethodSignature) joinPoint.getSignature();
      Method method = signature.getMethod();
      String name = signature.getName();
      LogTest logTest = signature.getMethod().getAnnotation(LogTest.class);
      String name1 = logTest.name();
      String type = logTest.type();
      System.out.println("method:"+method);
      System.out.println("name:"+name);
      System.out.println("name1:"+name1);
      System.out.println("type:"+type);
      return joinPoint.proceed();
  }
  @Before("log()")
  public void before(JoinPoint joinPoint){
      ServletRequestAttributes signature = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletRequest request = signature.getRequest();
      String ip = request.getRemoteHost();
      String remoteUser = request.getRemoteUser();
      System.out.println("ip:"+ip);
      System.out.println("user"+remoteUser);
  }

  @After("log()")
  public void after(JoinPoint point){
      System.out.println("跑完了");
  }


  @AfterThrowing("log()")
  public void after1(JoinPoint joinPoint){
      System.out.println("baocuole");
  }
}
 
posted @   Z_WINTER  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示