SpringBoot提供了強大AOP支持,我們前面講解過AOP面向切面,所以這里具體AOP原理就補具體介紹;
AOP切面主要是切方法,我們一般搞一些日志分析和事務操作,要用到切面,類似攔截器;
@Aspect注解是切面注解類
@Pointcut切點定義
@Before是方法執行前調用
@After是方法執行后調用
@AfterReturning方法執行返回值調用
Service層本身就可以切入事務,所以我們這類搞個常用的 切controller層方法
每個執行controller層的方法 都記錄下請求Url,訪問者IP 執行類方法參數等信息;
定義一個切面類:RequestAspect

1 package com.hik; 2 3 import javax.servlet.http.HttpServletRequest; 4 5 import org.apache.log4j.Logger; 6 import org.aspectj.lang.JoinPoint; 7 import org.aspectj.lang.annotation.After; 8 import org.aspectj.lang.annotation.AfterReturning; 9 import org.aspectj.lang.annotation.Aspect; 10 import org.aspectj.lang.annotation.Before; 11 import org.aspectj.lang.annotation.Pointcut; 12 import org.springframework.stereotype.Component; 13 import org.springframework.web.context.request.RequestContextHolder; 14 import org.springframework.web.context.request.ServletRequestAttributes; 15 16 @Aspect 17 @Component 18 public class RequestAspect { 19 20 private Logger log = Logger.getLogger(RequestAspect.class); 21 22 @Pointcut("execution(public * com.hik.controller.*.*(..))") 23 public void log() { 24 25 } 26 27 @Before("log()") 28 public void deoBefore(JoinPoint joinPoint) { 29 log.info("方法執行前..."); 30 ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 31 HttpServletRequest request=sra.getRequest(); 32 log.info("url:"+request.getRequestURI()); 33 log.info("ip:"+request.getRemoteHost()); 34 log.info("method:"+request.getMethod()); 35 log.info("class_method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); 36 log.info("args:"+joinPoint.getArgs()); 37 } 38 39 @After("log()") 40 public void doAfter(JoinPoint joinPoint){ 41 log.info("方法執行后..."); 42 } 43 44 @AfterReturning(returning="result",pointcut="log()") 45 public void doAfterReturning(Object result){ 46 log.info("執行返回值:"+result); 47 } 48 49 }
execution(public * com.hik.controller.*.*(..)) 這個定義 意思是 對 com.hik.controller包下的任意類,任意方法,任意參數,任意返回值的方法都進行切入
我們測試 StudentController
請求:http://localhost/studentAdd.html
點擊提交
控制台顯示:
這里得到了我們需要的信息;
當然這里用到了日志 springboot推薦logback log4j的升級版 用法基本差不多;