AOP总结(spring)
实现AOP流程:
Service s = new ServiceImpl(); //创建切入点Pointcut pc = new JdkRegexpMethodPointcut();//JdkRegexpMethodPointcut是切入点实现类。spring提供7个切入点实现类@1 //创建通知Advice advice = new SimpleAdvice();//SimpleAdvice实现了通知接口。srping提供5种通知接口@2 //创建通知者Advisor advisor = new DefaultPointcutAdvisor(pc,advice);//DefaultPointcutAdvisor是通知者实现类。spring提供3个通知者实现类@3 //创建代理ProxyFactory pf = new ProxyFactory();//spring支持两种代理@4 pf.addAdvisor(advisor); pf.setTarget(s); proxy = (Service)pf.getProxy(); proxy .doSomething();
?
?
?1、七种PointCut实现
Perl5RegexpMethodPointcut是一个最基本的正则表达式切入点, 它使用Perl 5正则表达式语法。 ? ComposablePointCut可组合切入点。可通过union()和intersection()等操作组合两个以上的切入点。 ? DynamicMethodMatcherPointcut流程切入点。 ? 动态切入和静态切入: ? ? ? BeforeAdvice 前置通知 ? ? ? AfterReturningAdvice 后置通知 ? ThrowsAdvice异常通知 ? ?IntroductionInterceptor?引入通知 ? ?调用的方法位于一个已经被引入接口里,这个引入拦截器将负责完成对这个方法的调用--因为它不能调用 ? ? 这里没有 ?CGLIB基于ASM框架生成字节码 1、首次创建CGLIB代理时,CGLIB会询问Spring每个方法应该如何处理。这意味着很多决定在JDK代理中每次invoke()调用时都要进行,但在CGLIB中只需要进行一次。CGLIB可以直接调用未被通知的方法,但JDK动态代理要去判断。 2、对于固定通知链的通知,CGLIB可以优化执行。 3、CGLIB对于被代理的方法,也使用了生成字节码的能力,执行被代理方法效率比JDK代理略微高。 ?<bean id="settersAndAbsquatulateAdvisor" name="code">class TestStaticPointcut extends StaticMethodMatcherPointcut { public boolean matches(Method m, Class targetClass) { // return true if custom criteria match } }public interface Pointcut { ClassFilter getClassFilter(); MethodMatcher getMethodMatcher();}public interface ClassFilter { boolean matches(Class clazz);}public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args);}public interface MethodInterceptor extends Interceptor {Object invoke(MethodInvocation invocation) throws Throwable;} public interface MethodBeforeAdvice extends BeforeAdvice { void before(Method m, Object[] args, Object target) throws Throwable; }public interface AfterReturningAdvice extends Advice { void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable; } public interface ThrowsAdviceextends AfterAdvice{ afterThrowing([Method, args, target], subclassOfThrowable) }public interface IntroductionInterceptor extends MethodInterceptor { boolean implementsInterface(Class intf); }public interface IntroductionAdvisor extends Advisor, IntroductionInfo { ClassFilter getClassFilter(); void validateInterfaces() throws IllegalArgumentException; } public interface IntroductionInfo { Class[] getInterfaces(); }<bean name="code">java.lang.reflect.Proxy.getProxyClass(loader, interfaces). getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler });