zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    object-c iOS 教程 git for mac
    mac Git本地服务器配置
    [转]XCode中修改缺省公司名称/开发人员名称
    IOS------Warning
    Linux---CentOS 定时运行脚本配置练手
    微信公众号一些错误的原因错误代码41001
    微信支付的一些新的经验总结
    关于THINKPHP5模型关联的初步理解
    写下thinkphp5和thinkphp3.2的不同
    练手THINKPHP5过程和bootstrap3.3.7
  • 原文地址:https://www.cnblogs.com/zxg-blog/p/10233064.html
Copyright © 2011-2022 走看看