Springboot 如何使用AOP同时织入多个切面?实现用户 操作日志记录功能

版权声明:转载请标明出处 https://blog.csdn.net/Joe_Wang1/article/details/82378576

首先导入AOP的pom

  <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标识的方法进行切面,调用某个方法 也会在控制台输出,达到操作日志记录的效果

猜你喜欢

转载自blog.csdn.net/Joe_Wang1/article/details/82378576
今日推荐