springboot 引入AOP 切面 @Aspect 註解使用
阿新 • • 發佈:2021-06-21
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
*/ @Aspect @Component @Slf4j public class HttpAspect { /** * 日誌切點 */ @Pointcut("execution(public * com.api.controller..*.*(..))") public void log() { } /** * 開始請求前 * * @param joinPoint */ @Before("log()") public void doBefore(JoinPoint joinPoint) { // 主類 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null){ HttpServletRequest request = attributes.getRequest(); // url 路徑 log.info("請求={}", request.getRequestURL() + " | method=" + request.getMethod() + " | ip=" + request.getRemoteAddr()); // 類方法 log.info("方法={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); // 引數 log.info("引數={}", Arrays.toString(joinPoint.getArgs())); } } /** * 返回處理 * * @param result */ @AfterReturning(returning = "result", pointcut = "log()") public void doAfterReturning(Object result) { log.info("返回={}", JSON.toJSON(result)); }
任何的public方法
execution(public * *(..))
以set開始的方法
execution(* set*(..))
定義在cn.freemethod.business.pack.Say介面中的方法
execution(* cn.freemethod.business.pack.Say.*(..))
任何cn.freemethod.business包中的方法
execution(* cn.freemethod.business.*.*(..))
任何定義在com.xyz.service包或者其子包中的方法
execution(* cn.freemethod.business..*.*(..))
其他表示式
任何在com.xyz.service包中的方法
within(com.xyz.service.*)
任何定義在com.xyz.service包或者其子包中的方法
within(com.xyz.service..*)
任何實現了com.xyz.service.AccountService介面中的方法
this(com.xyz.service.AccountService)
任何目標物件實現了com.xyz.service.AccountService的方法
target(com.xyz.service.AccountService)
一般情況下代理類(Proxy)和目標類(Target)都實現了相同的介面,所以上面的2個基本是等效的。
有且只有一個Serializable引數的方法
args(java.io.Serializable)
只要這個引數實現了java.io.Serializable介面就可以,不管是java.io.Serializable還是Integer,還是String都可以。
目標(target)使用了@Transactional註解的方法
@target(org.springframework.transaction.annotation.Transactional)
目標類(target)如果有Transactional註解中的所有方法
@within(org.springframework.transaction.annotation.Transactional)
任何方法有Transactional註解的方法
@annotation(org.springframework.transaction.annotation.Transactional)
有且僅有一個引數並且引數上型別上有Transactional註解
@args(org.springframework.transaction.annotation.Transactional)
注意是引數型別上有Transactional註解,而不是方法的引數上有註解。
bean的名字為tradeService中的方法
bean(simpleSay)
bean名字為simpleSay中的所有方法。
bean名字能匹配
bean(*Impl)
bean名字匹配*Impl的bean中的所有方法。