Spring_Spring与AOP_AspectJ基于XML的实现

时间:2021-08-16 02:23:25

一、前置通知

 import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; @Aspect //表示当前类为切面
public class MyAspect {
@Before("execution(* *..ISomeService.doFirst(..))")
public void myBefore(){
System.out.println("执行前置通知方法");
} @Before("execution(* *..ISomeService.doFirst(..))")
public void myBefore(JoinPoint jp){
System.out.println("执行前置通知方法 jp="+jp);
} @AfterReturning("execution(* *..ISomeService.doSecond(..))")
public void myAfterReturning(){
System.out.println("执行后置通知方法"); } @AfterReturning(value="execution(* *..ISomeService.doSecond(..))",returning="result")
public void myAfterReturning(Object result){
System.out.println("执行后置通知方法 result="+result); } @Around("execution(* *..ISomeService.doSecond(..))")
public Object myAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("执行环绕通知方法,目标方法执行之前");
//执行目标方法
Object result = pjp.proceed();
System.out.println("执行环绕通知方法,目标方法执行之后");
if(result !=null){
result=((String)result).toUpperCase();
}
return result;
} @AfterThrowing(value="execution(* *..ISomeService.doThird(..))",throwing="ex")
public void myAfterThrowing(Exception ex){
System.out.println("执行异常通知方法ex="+ex.getMessage());
} @After("doThirdPointcut()")
public void myAfter(){
System.out.println("执行最终通知方法");
}
//定义了一个切入点,叫doThirdPointcut()
@Pointcut("execution(* *..ISomeService.doThird(..))")
public void doThirdPointcut(){}
}

MyAspect

<!-- 注册切面 -->
<bean id="myAspect" class="com.bjpowernode.xml.MyAspect"></bean>
<!-- 注册目标对象 -->
<bean id="someService" class="com.bjpowernode.xml.SomeServiceImpl"></bean>
<!-- AOP配置 -->
<aop:config>
<aop:pointcut expression="execution(* *..ISomeService.doFirst(..))" id="doFirstPointcut"/>
<aop:pointcut expression="execution(* *..ISomeService.doSecond(..))" id="doSecond1Pointcut"/>
<aop:pointcut expression="execution(* *..ISomeService.doThird(..))" id="doThirdPointcut"/>
<aop:aspect ref="myAspect">
<aop:before method="myBefore" pointcut-ref="doFirstPointcut"/>
<aop:before method="myBefore(org.aspectj.lang.JoinPoint)" pointcut-ref="doFirstPointcut"/>
</aop:aspect>
</aop:config>

二、后置通知

           <aop:after-returning method="myAfterReturning" pointcut-ref="doSecondPointcut"/>
<aop:after-returning method="myAfterReturning(java.lang.Object)" pointcut-ref="doSecondPointcut" returning="result" />

三、环绕通知

 <aop:around method="myAround" pointcut-ref="doSecondPointcut"/>

四、异常通知

 <aop:after-throwing method="myAfterThrowing(java.lang.Exception)" pointcut-ref="doThirdPointcut" throwing="ex"/>

五、最终通知

<aop:after method="myAfter" pointcut-ref="doThirdPointcut"/>