spring AoP学习 -----AoP织入器

it2025-04-13  8

  在spring AoP中,使用类aop.framework.ProxyFactory作为织入器,使用ProxyFactory作为织入器,使用ProxyFactory来进行横切逻辑的织入很简单,spring AoP是基于代理模式的AoP实现,织入过程实现完成后,会返回织入了横切逻辑的目标对象的代理对象,ProxyFactory就会返回那个织入完成的代理对象。

  使用ProxyFactory只需要指定如下两个最基本的东西:1.指定要对其进行织入的对象。2.指定要应用到目标对象的Aspect

  ProxyFactory代理类型:

    1.基于接口的代理

eg:

public class WeaveTest { @Test public void weaveTest(){ WeaveIMockTaskImpl weaveIMockTaskImpl = new WeaveIMockTaskImpl(); ProxyFactory weaver = new ProxyFactory(weaveIMockTaskImpl); //weaver.setInterfaces(new Class[]{WeaveITask.class});//在没有其他属性的情况下,可以不用指定接口 NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(); advisor.setMappedName("execute"); //MethodBeforeAdvice beforeAdvice = new WeaveMethodBeforeAdvice(); //advisor.setAdvice(beforeAdvice); advisor.setAdvice(new WeavePerformanceMethodInterceptor()); weaver.addAdvisor(advisor); WeaveITask weaveITask = (WeaveITask)weaver.getProxy(); weaveITask.execute(); } }

proxyFactory为织入器,WeaveIMockImpl为一个实现至少一个接口的实现类,通过setMapperName指定织入的方法名称,WeavePerformanveMethodInterceptor为一个AroundAdvice的Advice,通过getProxy方法获取代理。

      2.基于类的代理:

eg:

public class WeaveTestWithoutInterface { @Test public void weaveTest(){ ProxyFactory proxyFactory = new ProxyFactory(new WeaveWithoutInterfaceExecute()); NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(); //advisor.setMappedName("execute"); advisor.setMappedNames(new String[]{"execute","execute2"}); advisor.setAdvice(new WeavePerformanceMethodInterceptor()); proxyFactory.addAdvisor(advisor); WeaveWithoutInterfaceExecute proxyObject = (WeaveWithoutInterfaceExecute)proxyFactory.getProxy(); proxyObject.execute(); proxyObject.execute2(); System.out.println(proxyObject.getClass() ); } }

  当织入目标类至少实现了一个接口,proxyFactory默认使用基于接口的代理,如果出现了下面三种情况的任何一种,将使用基于类的代理:

    1.目标类没有实现任何接口的情况下

    2.ProxyFactory的proxyTargetClass属性值设置为true

    3.proxyFactory的optimize属性值被设置为true

    

 

    3.Introduction的织入

      Introduction可以为已经存在的对象类型添加新的行为,只能应用于对象级别的拦截,只能通过接口定义为当前对象添加新的行为。

转载于:https://www.cnblogs.com/Qbright/archive/2012/07/25/2608115.html

最新回复(0)