1. 程式人生 > >Springboot 如何使用AOP同時織入多個切面?實現使用者 操作日誌記錄功能

Springboot 如何使用AOP同時織入多個切面?實現使用者 操作日誌記錄功能

首先匯入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標識的方法進行切面,呼叫某個方法 也會在控制檯輸出,達到操作日誌記錄的效果