introduction為對(duì)象動(dòng)態(tài)的加入原先所沒(méi)有的職責(zé)。

          例子:
          系統(tǒng)中已經(jīng)有如下的類(lèi):
          接口
          package?cn.blogjava.introduction;

          public?interface?ISome?{
          ????
          public?void?doSome();
          }
          類(lèi)
          package?cn.blogjava.introduction;

          public?class?Some?implements?ISome?{

          ????
          public?void?doSome()?{
          ????????System.out.println(
          "do?some");

          ????}

          }

          希望給Some類(lèi)增加doOther()方法,可以通過(guò)IntroductionInterceptor來(lái)完成任務(wù)。
          首先定義接口
          package?cn.blogjava.introduction;

          public?interface?IOther?{
          ????
          public?void?doOther();
          }

          實(shí)現(xiàn)IntroductionInterceptor接口:
          package?cn.blogjava.introduction;

          import?org.aopalliance.intercept.MethodInvocation;
          import?org.springframework.aop.IntroductionInterceptor;

          public?class?OtherIntroduction?implements?IOther,?IntroductionInterceptor?{

          ????
          public?void?doOther()?{
          ????????System.out.println(
          "do?other");

          ????}

          ????
          public?Object?invoke(MethodInvocation?methodInvocation)?throws?Throwable?{
          ????????
          if(implementsInterface(methodInvocation.getMethod().getDeclaringClass()))?{
          ????????????
          return?methodInvocation.getMethod().invoke(this,?methodInvocation.getArguments());
          ????????}?
          else?{
          ????????????
          return?methodInvocation.proceed();
          ????????}
          ????}

          ????
          public?boolean?implementsInterface(Class?aclass)?{
          ????????
          return?aclass.isAssignableFrom(IOther.class);
          ????}

          }

          測(cè)試類(lèi):
          package?cn.blogjava.introduction;

          import?org.springframework.context.ApplicationContext;
          import?org.springframework.context.support.FileSystemXmlApplicationContext;

          public?class?SpringAOPDemo?{

          ????
          public?static?void?main(String[]?args)?{
          ????????ApplicationContext?context?
          =?
          ????????????
          new?FileSystemXmlApplicationContext("beans-config.xml");
          ????????
          ????????ISome?some?
          =?(ISome)context.getBean("proxyFactoryBean");
          ????????some.doSome();
          ????????
          ????????((IOther)some).doOther();

          ????}

          }
          posted on 2006-08-18 15:20 knowhow 閱讀(790) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): Framework

          只有注冊(cè)用戶(hù)登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 平原县| 乌海市| 侯马市| 义马市| 襄垣县| 湖北省| 盐边县| 肥乡县| 泗水县| 延川县| 裕民县| 镇赉县| 宝应县| 扶余县| 宁南县| 永昌县| 西林县| 聂拉木县| 新闻| 盐山县| 阿拉尔市| 雷波县| 永新县| 时尚| 华阴市| 惠东县| 云和县| 宁夏| 朝阳区| 昆明市| 喀喇沁旗| 通海县| 黄浦区| 苍梧县| 紫云| 辽宁省| 阳信县| 兴业县| 临高县| 景洪市| 林周县|