pom添加依賴:java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.tx.gelv.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @author:hgt
* @version:1.0
* @date:2020/5/14
* @description:com.tx.gelv.aspect
* aop 面向切面編程
*/
/**
* @Component
* 引入到spring容器內
*/
@Aspect
@Component
public class HttpAspect {
// /**
// * **********************type1*******************************************
// */
// //對方法和類進行攔截,在目標運行以前
// @Before("execution(public * com.tx.gelv.controller.Test.index(..))")
// public void beforelogs(){
// System.out.println("1111");
// }
//
// //對方法和類進行攔截,在目標運行以後
// @After("execution(public * com.tx.gelv.controller.Test.index(..))")
// public void afterlogs(){
// System.out.println("2222");
// }
/**
* ***************************type2**********************************
*/
//自帶日誌log4j
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.tx.gelv.controller.Test.*(..))")
public void log(){
}
@Before("log()")
public void before(JoinPoint joinPoint){
logger.info("***********aspect********before*************start***************");
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}",request.getRequestURL());
//method
logger.info("method={}",request.getMethod());
//ip
logger.info("ip={}",request.getRemoteAddr());
//類方法
logger.info("class-method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
//參數
logger.info("args:{}",joinPoint.getArgs());
logger.info("***********aspect********before**********stop*******************");
}
@After("log()")
public void after(){
logger.info("22222222");
}
/**
* 用於返回對象信息
* @param object
*/
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
logger.info("response={}",object);
}
}
實現圖片:
後續將持續更新