Spring之基于Schema形式的AOP实现

一、创建LogSchema.java:

package org.ruangong.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class LogSchema {

public void afterReturning(JoinPoint jp,Object returnValue) throws Throwable {
// TODO Auto-generated method stub
System.out.println("(Schema)后置通知....目标对象:"+jp.getThis()+",调用的方法:"+jp.getSignature().getName()+",方法的参数的个数:"+jp.getArgs().length+",返回值:"+returnValue);
}

public void before(){
System.out.println("(Schema)前置通知...");
}
public void whenException(JoinPoint jp,NullPointerException e){
System.out.println("(Schema)异常通知..."+e.getMessage());
}
public Object around(ProceedingJoinPoint jp){
System.out.println("(Scheam)环绕通知:前置通知。。。。。。");
Object result = null;
try{
result = jp.proceed();
System.out.println("(Scheam)环绕通知:后置通知。。。。。。");
}catch(Throwable e){
System.out.println("(Scheam)环绕通知:异常通知。。。。。。");
}
return result;
}
}

  在这里一定要注意,利用注解或者Schema实现aop一定要把后置通知参数改为JoinPoint jp。

在applicationContext.xml文件中添加:

<!-- Schema实现通知 -->
<bean id="logSchema" class="org.ruangong.aop.LogSchema"></bean>

<aop:config>
<aop:pointcut expression="execution(public void org.ruangong.service.impl.StudentServiceImpl.addStudent(org.ruangong.entity.Student))" id="pcSchema"/>
<!-- <aop:advisor advice-ref="logSchema" pointcut-ref="pcSchema"/> -->
<!-- Schema方式 -->
<aop:aspect ref="logSchema">
<aop:before method="before" pointcut-ref="pcSchema"/>
<aop:after-returning method="afterReturning" returning="returnValue" pointcut-ref="pcSchema"/>
<aop:after-throwing method="whenException" throwing="e" pointcut-ref="pcSchema"/>
<!-- 环绕通知 -->
<aop:around method="around" pointcut-ref="pcSchema"/>
</aop:aspect>
</aop:config>

  实现测试类:

 

posted @ 2020-11-16 20:54  Double晨  阅读(143)  评论(0)    收藏  举报