spring 提供了 2 种 AOP 实现方式:(1)Schema-based ,(2)AspectJ
Schema-based:每个通知都需要实现接口或类,配置 spring 配置文件时在aop:config配置
新建通知类:
前置通知,后置通知,环绕通知,异常通知(AspectJ有最终通知):
每个通知都要有自己类,因为它们所继承的接口不同,
前置通知继承org.springframework.aop.MethodBeforeAdvice;
后置通知继承org.springframework.aop.AfterReturningAdvice;
环绕通知继承org.aopalliance.intercept.MethodInterceptor;
异常通知继承org.springframework.aop.ThrowsAdvice;
arg0: 切点方法对象 Method 对象
arg1: 切点方法参数
arg2:切点在哪个对象中
前置:
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyMethodBeforeAdvice implements MethodBeforeAdvice{
/**
*
*/
@Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
// TODO Auto-generated method stub
System.out.println("这是前置通知");
}
}
后置:
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
public class MyMethodAfterAdvice implements AfterReturningAdvice{
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
// TODO Auto-generated method stub
System.out.println("这是后置通知");
}
}
环绕:
import