1. 前置增强,在核心功能之前执行的额外功能
public class MyBeforeAdvice implements MethodBeforeAdvice{ @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.print("this is my before advice!"); String methodName = arg0.getName(); System.out.print("methodName"+methodName); //获取目标方法的参数的实参 for(int i = 0;i< arg1.length;i++){ System.out.print("arg1:"+arg1[i]); } //获取目标类路径名 System.out.print("classPath:"+arg2.getClass()); } }
2. 后置增强,在核心功能之后执行的额外功能
public class MyAfterAdvice implements AfterReturningAdvice{ @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { //获取反参参数的类型 System.out.print("the arg0:"+arg0.getClass()); //获取目标方法名 System.out.print("the arg1:"+arg1.getName()); //获取目标方法参数的实参列表 for(int i = 0;i<arg2.length;i++){ System.out.print("the arg2:"+arg2[i]); } //获取目标实现类的类路径 System.out.print("the args3:"+arg3.getClass()); System.out.print("this is AfterReturning advice"); } }
3. 异常增强,在核心功能发生异常时执行的额外功能,先捕获,后抛出
package com.nz.aop; import org.springframework.aop.ThrowsAdvice; import java.lang.reflect.Method; public class MyThrowsAdvice implements ThrowsAdvice { public void afterThrowing(Method method, Object[] args, Object target,Exception ex){ System.out.print(target+"里面的"+method.getName()+"产生了"+ex.getMessage()); } }
4. 环绕增强,在核心功能之前以及之后执行的额外功能
public class MyInterceptor implements MethodInterceptor{ @Override public Object invoke(MethodInvocation arg0) throws Throwable { System.out.print("this is my interceptor"); //获取目标实现类对象 System.out.print("arg0.getThis():"+arg0.getThis().getClass().toString()); //获取目标方法名称 System.out.print("arg0.getMethod():"+arg0.getMethod().getName()); //获取目标方程参数的实参列表 Object[] arguments = arg0.getArguments(); for(int i=0;i<arguments.length;i++){ System.out.print("arg0.getArguments():"+arguments[i]); } //由于启动了环绕增强,目标类的方法将不会被执行,而被.proceed取代,并返回目标类的反参 //执行目标方法 Object object = arg0.proceed(); return object; } }