环绕增强允许在目标类方法调用前后织入横切逻辑,它
综合实现了前置、后置增强两者的功能。
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* @author Chris Yu
*
* @CreateTime 2014-5-12 下午10:25:37
*/
public class GreetingInterceptor implements MethodInterceptor {
/*
* (非 Javadoc)
*
* 截获目标类方法的执行,并在前后添加横切逻辑
*
* @see
* org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
* .MethodInvocation)
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] args = invocation.getArguments();
String clientName = (String) args[0];
// 在目标方法执行前调用
System.out.println("How are you! Mr." + clientName);
// 通过反射机制调用目标方法
Object object = invocation.proceed();
// 在目标方法执行后调用
System.out.println("Please enjoy yourself!");
return object;
}
import org.aopalliance.intercept.MethodInvocation;
/**
* @author Chris Yu
*
* @CreateTime 2014-5-12 下午10:25:37
*/
public class GreetingInterceptor implements MethodInterceptor {
/*
* (非 Javadoc)
*
* 截获目标类方法的执行,并在前后添加横切逻辑
*
* @see
* org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
* .MethodInvocation)
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object[] args = invocation.getArguments();
String clientName = (String) args[0];
// 在目标方法执行前调用
System.out.println("How are you! Mr." + clientName);
// 通过反射机制调用目标方法
Object object = invocation.proceed();
// 在目标方法执行后调用
System.out.println("Please enjoy yourself!");
return object;
}
}
spring 直接使用AOP联盟所定义的MethodInterceptor作为环绕增强的接口。该接口拥有唯一的接口方法Object invoke(MethodInvocation invocation) throws Throwable,MethodInvocation 不但封装目标类方法及其入参数组,还封装了目标方法所在的实例对象,通过Methodinvocation的getArguments()可以获取目标方法的入参数组,通过procced()反射调用目标实例相应的方法。