1、引入jar包spring
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
實現操做日誌記錄的功能,無非就是監控用戶調用了哪些方法。AOP是一個不錯的選擇,接下來介紹一下,AOP怎麼對每一個方法都實施切面。session
1.自定義註解app
/**
* 自定義Log註解 用於切面標識
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
2.將須要切面的 方法 都標註 該註解@Logspring-boot
@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標識的方法進行切面.net
@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 日誌