0
点赞
收藏
分享

微信扫一扫

SpringAOP应用及其原理

Gascognya 2021-10-15 阅读 108
技术分享

AOP

  • 切面(Aspect)
    切面简单理解就是一个类,这个类里面定义了通知与切点,通知用@Aspect和@Component注解。
  • 通知(advice)
    @Before:前置通知,在目标方法被调用之前调用通知功能。
    @After:后置通知,在目标方法执行结束后,无论执行结果如何都执行通知定义的任务。
    @After-returning:后置通知,在目标方法执行结束后,如果执行成功,则执行通知定义的任务。
    @After-throwing:异常通知,如果目标方法执行过程中抛出异常,则执行通知定义的任务。
    @Around:环绕通知,在目标方法执行前和执行后,都需要执行通知定义的任务。
  • 切点(PointCut)
    切点就是要告知程序在执行哪些类、方法时执行自定义的各种通知。切点通常是用AspectJ表达式来定义切点。
// 第一个*表示方法的任意返回值类型,..表示方法使用的参数任意。
execution(* com.demo.service.AspectJDemoService.sayHello(..))
// 第一个*表示方法的任意返回值类型,第二个*表示AspectJDemoService类的任意方法,..表示方法使用的参数任意。
execution(* com.demo.service.AspectJDemoService.*(..))
// 第一个*表示方法的任意返回值类型,第二个*.*表示service包下的任意类的任意方法,..表示方法使用的参数任意。
execution(* com.demo.service.*.*(..))

AOP应用(日志)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.4.1</version>
</dependency>
<dependency>
  <groupId>eu.bitwalker</groupId>
  <artifactId>UserAgentUtils</artifactId>
</dependency>
spring:
  aop:
    auto: true #相当于标注了@EnableAspectJAutoProxy
    proxy-target-class: true #开启cglib代理
@Aspect
@Component
@Slf4j
public class AopLog {
    private static final String START_TIME = "request-start";

    /**
     * 切入点
     */
    @Pointcut("execution(* com.icode.controller.*Controller.*(..))")
    public void log() {

    }

    /**
     * 前置操作
     *
     * @param point 切入点
     */
    @Before("log()")
    public void beforeLog(JoinPoint point) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        log.info("【请求URL】:{}", request.getRequestURL());
        log.info("【请求IP】:{}", request.getRemoteAddr());
        log.info("【请求类名】:{},【请求方法名】:{}", point.getSignature().getDeclaringTypeName(), point.getSignature().getName());

        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("【请求参数】:{},", JSONUtil.toJsonStr(parameterMap));
        Long start = System.currentTimeMillis();
        request.setAttribute(START_TIME, start);
    }

    /**
     * 环绕操作
     *
     * @param point 切入点
     * @return 原方法返回值
     * @throws Throwable 异常信息
     */
    @Around("log()")
    public Object aroundLog(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        log.info("【返回值】:{}", JSONUtil.toJsonStr(result));
        return result;
    }

    /**
     * 后置操作
     */
    @AfterReturning("log()")
    public void afterReturning() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

        Long start = (Long) request.getAttribute(START_TIME);
        Long end = System.currentTimeMillis();
        log.info("【请求耗时】:{}毫秒", end - start);

        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
    }
}
@RestController
@Slf4j
public class TestController {

    /**
     * 测试方法
     *
     * @param who 测试参数
     * @return {@link Dict}
     */
    @GetMapping("/test")
    public Dict test(String who) {
        log.info("/test方法调用开始...");
        return Dict.create().set("who", StrUtil.isBlank(who) ? "me" : who);
    }
}

AOP原理

举报

相关推荐

0 条评论