• springboot使用aop做日志


    一、引入jar包

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    实现操作日志记录的功能,无非就是监控用户调用了哪些方法。AOP是一个不错的选择,接下来介绍一下,AOP怎么对每个方法都实施切面。

    1.自定义注解

    /**
    * 自定义Log注解 用于切面标识
    */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Log {
    String value() default "";
    }
    2.将需要切面的 方法 都标注 该注解@Log


    @Log("删除用户")
    @RequestMapping(value = "deleteAccount.do", method = RequestMethod.POST)
    @ResponseBody
    public Map deleteAccounnt(Integer id) {
    Integer deleteAccount = loginService.deleteAccount(id);
    if (deleteAccount > 0) {
    resultMap.put("status", "200");
    resultMap.put("message", "账号 删除成功");
    } else {
    resultMap.put("status", "500");
    resultMap.put("message", "账号 删除失败");
    }
    return resultMap;
    }
    3.将有Log标识的方法进行切面

    @Component
    @Aspect
    public class LogAspect {

    @Autowired
    LoginlogService loginlogService;

    @Pointcut("@annotation(Log)") //将Log标识的方法进行切面
    public void logAsppect3() {
    }

    @AfterReturning("logAsppect3()")
    public void logAsppect(JoinPoint jp) throws Throwable {

    try {

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes != null) {
    HttpServletRequest request = attributes.getRequest();
    HttpSession session = request.getSession(true);
    String email = (String) session.getAttribute("email");

    //JoinPoint 对象可以获取目标业务方法的详细信息:方法签名,调用参数
    Signature m = jp.getSignature();
    //方法名
    String methodName = m.getName();
    MethodSignature signature = (MethodSignature) jp.getSignature();
    Method method = signature.getMethod();
    Log log = method.getAnnotation(Log.class);
    System.out.println("Log Value:" + log.value());//输出注解里面的值
    System.out.println("操作人 :" + email + "正在执行方法 :" + methodName);


    }

    } catch (Exception e) {

    e.printStackTrace();
    }

    }

    }
    4.这样就可以 对所有@Log标识的方法进行切面,调用某个方法 也会在控制台输出,达到操作日志记录的效果
    原文:https://blog.csdn.net/Joe_Wang1/article/details/82378576

  • 相关阅读:
    TypeScript-基础-09-声明文件
    TypeScript-基础-08-类型断言
    TypeScript-基础-07-函数的类型
    TypeScript-基础-06-数组的类型
    TypeScript-基础-05-对象的类型—接口
    TypeScript-基础-04-联合类型
    TypeScript-工程
    小白学前端03
    小白学前端02
    小白学前端
  • 原文地址:https://www.cnblogs.com/zxg-blog/p/10233064.html
Copyright © 2020-2023  润新知