Spring AOP 切面@Around注解的具体使用

@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务。

比如我们想在执行controller中方法前打印出请求参数,并在方法执行结束后来打印出响应值,这个时候,我们就可以借助于@Around注解来实现;

再比如我们想在执行方法时动态修改参数值等

类似功能的注解还有@Before等等,用到了Spring AOP切面思想,Spring AOP常用于拦截器、事务、日志、权限验证等方面。

完整演示代码如下:

需要说明的是,在以下例子中,我们即可以只用@Around注解,并设置条件,见方法run1();也可以用@Pointcut和@Around联合注解,见方法pointCut2()和run2(),这2种用法是等价的。如果我们还想利用其进行参数的修改,则调用时必须用joinPoint.proceed(Object[] args)方法,将修改后的参数进行回传。如果用joinPoint.proceed()方法,则修改后的参数并不会真正被使用。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.persistence.EntityManager;
 
/**
 * 控制器切面
 *
 * @author lichuang
 */
 
@Component
@Aspect
public class ControllerAspect {
 
    private static final Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
 
    @Autowired
    private EntityManager entityManager;
 
    /**
     * 调用controller包下的任意类的任意方法时均会调用此方法
     */
    @Around("execution(* com.company.controller.*.*(..))")
    public Object run1(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法参数值数组
        Object[] args = joinPoint.getArgs();
        //得到其方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法参数类型数组
        Class[] paramTypeArray = methodSignature.getParameterTypes();
        if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
            //如果方法的参数列表最后一个参数是entityManager类型,则给其赋值
            args[args.length - 1] = entityManager;
        }
        logger.info("请求参数为{}",args);
        //动态修改其参数
        //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)
        Object result = joinPoint.proceed(args);
        logger.info("响应结果为{}",result);
        //如果这里不返回result,则目标对象实际返回值会被置为null
        return result;
    }
 
    @Pointcut("execution(* com.company.controller.*.*(..))")
    public void pointCut2() {}
 
    @Around("pointCut2()")
    public Object run2(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法参数值数组
        Object[] args = joinPoint.getArgs();
        //得到其方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法参数类型数组
        Class[] paramTypeArray = methodSignature.getParameterTypes();
        if (EntityManager.class.isAssignableFrom(paramTypeArray[paramTypeArray.length - 1])) {
            //如果方法的参数列表最后一个参数是entityManager类型,则给其赋值
            args[args.length - 1] = entityManager;
        }
        logger.info("请求参数为{}",args);
        //动态修改其参数
        //注意,如果调用joinPoint.proceed()方法,则修改的参数值不会生效,必须调用joinPoint.proceed(Object[] args)
        Object result = joinPoint.proceed(args);
        logger.info("响应结果为{}",result);
        //如果这里不返回result,则目标对象实际返回值会被置为null
        return result;
    }
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Around是Spring AOP中的一个注解,用于定义环绕通知。环绕通知是在被通知的方法执行前后都会执行的通知。它可以控制被通知方法的执行,并可以在执行前后进行一些额外的处理逻辑。[1] 在使用@Around注解时,需要编写一个环绕通知方法,方法需要带有ProceedingJoinPoint类型的参数。ProceedingJoinPoint参数可以让我们在通知方法中控制被通知方法的执行,例如在方法执行前后打印日志、计算执行耗时等操作。通过调用ProceedingJoinPoint的proceed()方法,可以继续执行被通知方法,也可以在此中断方法的执行。 例如,下面是一个使用@Around注解的示例: ```java @Aspect @Component public class PerformanceAspect { @Around("execution(* com.example.MyService.myMethod(..))") public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long endTime = System.currentTimeMillis(); long executionTime = endTime - startTime; System.out.println("Execution Time: " + executionTime + "ms"); return result; } } ``` 以上示例中,使用@Around注解定义了一个名为measureExecutionTime的环绕通知方法。该方法接收一个ProceedingJoinPoint参数,通过调用proceed()方法执行被通知方法,并计算方法的执行耗时。最后,打印出执行时间。 请注意,上述示例中的切点表达式"execution(* com.example.MyService.myMethod(..))"需要根据实际情况进行修改,以匹配需要添加执行耗时的方法。 通过使用@Around注解,我们可以方便地在Spring AOP中实现对方法的执行耗时的监控和记录。<span class="em">1</span> #### 引用[.reference_title] - *1* [【注解Spring AOP 面向切面编程之@Around的详细用法](https://blog.csdn.net/weixin_44299027/article/details/124489435)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值