主要是想可以通过在方法上或者类上添加注解以达到增强的作用
1.以下主要是作用在方法上的
定义注解
package com.winning;
import java.lang.annotation.*;
/**
* @author lmx
* @date 2020/9/10 4:41 下午
* 接口切点注解,用于标记需要计量计次的接口
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface WinControllerPointCut {
}
创建切面类
package com.winning;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* @author lmx
* @date 2020/9/10 3:57 下午
*/
@Slf4j
@Aspect
@EnableAspectJAutoProxy
@Component
public class AopConfig {
/**
* 定义切点
* 该切点指向某个包,因此要求对应包内只有接口的方法,业务方法请分离到业务层
* 使用@annotation指定切点为 自定义注解接口com.winning.WinControllerPointCut
*/
@Pointcut("@annotation(com.winning.WinControllerPointCut)")
public void winPointCut() {
}
@Async
@Before("winPointCut()")
public void beforeCall(JoinPoint joinPoint) {
//前置通知-业务,入参需要切点方法定义好
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("before-接口路径:{}", request.getRequestURL().toString());
log.info("before-请求方式:{}", request.getMethod());
log.info("before-类方法:{}" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("before-请求参数 : {} " + Arrays.toString(joinPoint.getArgs()));
}
@Async
@AfterReturning(pointcut = "winPointCut()", returning = "resp")
public void calcNetflow(Object resp) {
//后置通知-业务,入参需要切点方法定义好
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("afterReturning-接口路径:{}", request.getRequestURL().toString());
}
}
在方法上使用注解
结果: