(入門SpringBoot)SpringBoot加接口操做日誌好方法(九)

用Spring的切面去作,慕課網上的大神的小妙招,被我拷貝下來了。
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.
*; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; /** * 做用實現攔截http請求. */ @Aspect @Component //把這個文件引入到Spring容器裏面去. public class HttpAspect { @Pointcut("execution(public * com.account.demo.controller.*.*(..))") public void log(){ } /** * 攔截那些方法.請求前. * JoinPoint 獲取類方法和類名對象. */ @Before("log()") public void logBefore(JoinPoint joinPoint){ System.out.println("攔截了getInfo方法"); //url,method,ip,類方法,參數. //SpringBoot經過RequestContextHolder獲取HttpRequest和HttpResponse ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //javax.servlet.http.HttpServletRequest HttpServletRequest request = attributes.getRequest(); System.out.println("url"+request.getRequestURL()); System.out.println("method"+request.getMethod()); System.out.println("ip"+request.getRemoteAddr()); //類方法. System.out.println("類方法"+joinPoint.getSignature().getDeclaringTypeName() +"."+ joinPoint.getSignature().getName() ); //參數: System.out.println("類方法"+joinPoint.getArgs()); } /** * 攔截那些方法.請求後. */ @After("log()") public void logAfter(){ System.out.println("攔截了getInfo方法.以後"); } /** * 返回參數. * @param object 入參 */ @AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ System.out.println(object); } }
相關文章
相關標籤/搜索