3-2-2:Spring中的环绕通知
一、环绕通知:
@around 是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式,Spring框架为我们提供了一个接口proceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法,还能返回一个Object类的结果。
二、使用方式
2 .1 基于注解:
@Aspect
public class AnnotationAround{
//使用@Pointcut注解声明切入点表达式
@Pointcut("execution(* *..service.doSome(..)") //所有包下service的doSome方法
public void mypt(){}
@Around("mypt()")
public Object myAround(ProceedingJoinPoint pjp){
Object rtValue = null; //得到方法执行所需的参数
System.out.println("方法执行前执行"); //前置
rtValue = pjp.proceed(); //执行业务层方法(切入点方法)
System.out.println("方法执行后执行"); //后置
return rtValue;
}
}
2.2 基于XML配置文件:
- 通知类
//去掉了所有的注解
public class AnnotationAround{
public Object aroundPringLog(ProceedingJoinPoint pjp){}
Object rtValue = null; //得到方法执行所需的参数
System.out.println("方法执行前执行"); //前置
rtValue = pjp.proceed(); //执行业务层方法(切入点方法)
System.out.println("方法执行后执行"); //后置
return rtValue;
}
}
- xml配置文件
<!--声明bean-->
<bean name="AnnotationAround" class="com.mypractice.util.AnnotationAround"/>
<!--配置切面及通知-->
<aop:config>
<aop:aspect ref="AnnotationAround">
<aop:pointcut id="mypt" expression="execution(* *..service.doSome(..))"/>
<aop:around method="myAround" pointcut-ref="mypt"/>
</aop:aspect>
</aop:config>

浙公网安备 33010602011771号