【注解】Spring AOP 面向切面编程之@Around的详细用法

本文目录

一、背景描述

二、AOP实例

三、@Around注解图文介绍


一、背景描述

在代码开发的过程中,总想看自己写的代码执行效率如何,每个方法的执行耗时是多少,但是在每个方法里添加耗时打印太麻烦,也不现实。不过幸好有 Spring 的面向切面编程。有了这个面向切面编程之后,那么,想要实现上述功能,一切就变得简单明了。

二、AOP实例

下面就上代码,其实很简单的一个类,代码没有几行:

package com.iotsoft.framework.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Aspect // @Aspect注解就是告诉 Spring 这是一个aop类,AOP切面
@Component
@Slf4j
public class LogAspect {

    @Autowired
    private Environment environment;

    /**
     * 用@Pointcut来注解一个切入方法
     * @Pointcut注解 声明这是一个需要拦截的切面,也就是说,当调用任何一个controller方法的时候,都会激活这个aop
     */
    @Pointcut("execution(public * com.iotsoft..*.*(..))")
    public void Pointcut() {
    }

    @Before("Pointcut()")
    public void beforeMethod(JoinPoint joinPoint) {
        String system = environment.getProperty("spring.application.system");
        String name = environment.getProperty("spring.application.name");
        if (system == null || "".equals(system)) {
            system = name;
        }
        MDC.put("system", system);
        MDC.put("app", name);
        MDC.put("host", HostUtils.getHostName());
        MDC.put("port", String.valueOf(HostUtils.getServerPort()));
    }

    @After("Pointcut()")
    public void afterMethod(JoinPoint joinPoint) {
        //MDC.clear();
    }

    /**
     * @Around注解 环绕执行,就是在调用目标方法之前和调用之后,都会执行一定的逻辑
     */
    @Around("Pointcut()")
    public Object Around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        // 调用执行目标方法(result为目标方法执行结果),必须有此行代码才会执行目标调用的方法(等价于@befor+@after),否则只会执行一次之前的(等价于@before)
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        log.debug(pjp.getTarget().getClass().getSimpleName() + "->" + pjp.getSignature().getName() + " 耗费时间:" + (end - start) + "毫秒");
        return result;
    }
}

三、@Around注解图文介绍

注意被@Around注解所在的方法:

方法中的注释《 // 否则只会执行一次之前的(等价于@before)”》:想表达的意思是如果不调用pjp.proceed()方法,这个@Around注解所表示的功能相当于@Before注解的功能,但是它这个方法里的内容该执行的还是会执行。

非常感谢《wysghmbb》博友提出的疑问。

执行结果查看

@After@Before 的解释可以看图片中,用法跟 @Around 一样。

完结!

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

No8g攻城狮

向每一个努力改变现状的你致敬!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值