spring-环绕通知 @Around 注解

环绕通知:常用于做事务,事务开启,执行方法。在目标方法执行之前之后执行。
被注解为环绕增强的方法要有返回值,Object类型。并且方法可以包含一个ProceedingJoinPoint 类型的参数。
接口ProceedingJoinPoint 有一个proceed()方法,用于执行目标方法。
若目标方法有返回值,则该方法的返回值就是目标方法的返回值。
最后,环绕增强方法将其返回值返回。该增强方法实际是拦截了目标方法的执行。

@Aspect //标注增强处理类(切面类)
@Component //交由Spring容器管理
@Order(0)  //设置优先级,值越低优先级越高
public class MyaspectJ {

  /*
    可自定义切点位置,针对不同切点,方法上的@Around()可以这样写
    如:@Around(value = "methodPointcut() && args(..)")
    
    //定义增强,pointcut连接点使用@annotation(xxx)进行定义
    @Pointcut(value = "@annotation(com.rq.aop.common.annotation.MyAnnotation)")
    public void methodPointcut(){}

    @Pointcut(value = "@annotation(com.rq.aop.common.annotation.MyAnnotation2)")
    public void methodPointcut2(){}
    */


    // 匹配方法执行连接点方式
    @Around(value = "execution(* *..SomeserviceImpl.Dofirst(..))")
    public Object myAspectJ(ProceedingJoinPoint pjd) throws Throwable {
    
        Object object =null;
        
        //a、在目标方法之前的功能增加
        System.out.println("调用的时间:"+new Date());
        
        // 1. 目标方法的调用
        object = pjd.proceed();

        //b、在目标方法之前的功能增加
        System.out.println("事务的调用");
        
		//修改目标方法的返回值
        object= object+"2020;
        return object;
    }
}

猜你喜欢

转载自blog.csdn.net/Little_Arya/article/details/129250462