spring AOP

来源:互联网 发布:2015旅游数据 编辑:程序博客网 时间:2024/05/18 03:31

在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() {@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println("before");}});pf.addAdvice(new AfterReturningAdvice() {@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target)throws Throwable {System.out.println("afterReturning:" + returnValue);}});pf.addAdvice(new org.aopalliance.intercept.MethodInterceptor() {@Overridepublic 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() {@Overridepublic 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 {@Overridepublic String hi(String name) {System.out.println("----HelloServiceImpl----hi");return "hello " + name;}@Overridepublic 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 aaaahello aaaa*****************************before--invoke before--advisor--invoke  before------HelloServiceImpl----addadvisor--invoke after----invoke after--afterReturning:77

通过这个例子可以简单理解一下aop的几个概念

advice为拦截后处理的逻辑,前置,后置,环绕等

pointcut为一个“过滤器”吧,配置需要拦截的方法

advisor为 advice和pointcut的合体


最后动态代理生成代理对象时候,使用java反射执行方法,顺便前后左后织入我们的拦截处理代码。