aop主要用於日誌記錄,跟蹤,優化和監控
下面是來自慕課網學習的一些案例,複製黏貼就完事了,注意類和方法的位置
pom新增依賴:
<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);
}
}
實現圖片:
後續將持續更新