概要
创建一个切入点PointcutAdvisor继承Spring的StaticMethodMatcherPointcutAdvisor
创建一个MethodInterceptor方法拦截器org.aopalliance.intercept.MethodInvocation
setAdvice(MethodInvocation mi)设置通知时传入一个MethodInterceptor方法拦截器
调用Demo
package com.wjz.demo; import org.springframework.aop.framework.ProxyFactory; import com.wjz.spring.CustomPointcutAdvisor; public class AopDemo { public static void main(String[] args) { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.addAdvisors(new CustomPointcutAdvisor()); proxyFactory.setTarget(new Foo()); Foo fooProxy = (Foo) proxyFactory.getProxy(); fooProxy.foo("wjz"); } }
PointcutAdvisor切入点
package com.wjz.spring; import java.lang.reflect.Method; import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; /** * 自定义方法切入点 * @author wjz * */ @SuppressWarnings("serial") public class CustomPointcutAdvisor extends StaticMethodMatcherPointcutAdvisor { public CustomPointcutAdvisor() { setAdvice(new CustomMethodInterceptor()); } @Override public boolean matches(Method method, Class<?> targetClass) { if ("foo".equals(method.getName())) { return true; } return false; } }
MethodInterceptor方法拦截器
package com.wjz.spring; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * 自定义方法拦截器 * @author wjz * */ public class CustomMethodInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("invoke method before"); Object arg = invocation.getArguments()[0]; System.out.println("arg " + arg); Object ti = invocation.getThis(); System.out.println("this " + ti); Method method = invocation.getMethod(); System.out.println("method " + method); System.out.println("toString " + toString()); Object result = invocation.proceed(); System.out.println("invoke method after"); return result; } }