• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
斑駁_光影
                              Keep Hunger     Keep Foolish
博客园    首页    新随笔    联系   管理    订阅  订阅

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

  在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可以为已经存在的对象类型添加新的行为,只能应用于对象级别的拦截,只能通过接口定义为当前对象添加新的行为。

posted @ 2012-07-25 13:15  斑驳_光影  阅读(1369)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3