在spring事务里面,看到了spring在beanProcessor的AbstractAutoProxyCreator包装了bean,使用了jdk或者cglib动态代理,最后使用到了ProxyFactory
那么只要我们准备了必要的参数,可以使用这个类生成代理类
package com.test.aop;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
public class TestAop {
public static void main(String[] args) {
Class[] interfaces = new Class[] { HelloService.class };
ProxyFactory pf = new ProxyFactory(interfaces);
pf.setTarget(new HelloServiceImpl());
pf.setOpaque(true);
pf.addAdvice(new MethodBeforeAdvice() {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("before");
}
});
pf.addAdvice(new AfterReturningAdvice() {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
throws Throwable {
System.out.println("afterReturning:" + returnValue);
}
});
pf.addAdvice(new org.aopalliance.intercept.MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("--invoke before--");
Object proceed = invocation.proceed();
System.out.println("--invoke after--");
return proceed;
}
});
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
advisor.addMethodName("add");
advisor.setAdvice(new org.aopalliance.intercept.MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("advisor--invoke before--");
Object proceed = invocation.proceed();
System.out.println("advisor--invoke after--");
return proceed;
}
});
pf.addAdvisor(advisor);
HelloService proxy = (HelloService) pf.getProxy();
System.out.println(proxy.hi("aaaa"));
System.out.println("*****************************");
System.out.println(proxy.add(2, 5));
}
}
package com.test.aop;
public class HelloServiceImpl implements HelloService {
@Override
public String hi(String name) {
System.out.println("----HelloServiceImpl----hi");
return "hello " + name;
}
@Override
public int add(int a, int b) {
System.out.println("----HelloServiceImpl----add");
return a + b;
}
}
打印
[2017-09-15 21:00:28.918] [main] [DEBUG] JdkDynamicAopProxy: Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [com.test.aop.HelloServiceImpl@273305]
before
--invoke before--
----HelloServiceImpl----hi
--invoke after--
afterReturning:hello aaaa
hello aaaa
*****************************
before
--invoke before--
advisor--invoke before--
----HelloServiceImpl----add
advisor--invoke after--
--invoke after--
afterReturning:7
7
通过这个例子可以简单理解一下aop的几个概念
advice为拦截后处理的逻辑,前置,后置,环绕等
pointcut为一个“过滤器”吧,配置需要拦截的方法
advisor为 advice和pointcut的合体
最后动态代理生成代理对象时候,使用java反射执行方法,顺便前后左后织入我们的拦截处理代码。