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)航:
           
          主站蜘蛛池模板: 嵊州市| 遂昌县| 泾川县| 阿拉善右旗| 大名县| 天祝| 长汀县| 普定县| 额尔古纳市| 伊宁县| 呼和浩特市| 西宁市| 历史| 法库县| 黄山市| 新野县| 巴青县| 城固县| 永川市| 郁南县| 定陶县| 盖州市| 理塘县| 黄梅县| 连云港市| 宁阳县| 石林| 扶沟县| 禄劝| 永定县| 蓬安县| 泗阳县| 华蓥市| 华池县| 乾安县| 汝南县| 英德市| 丹阳市| 普定县| 湄潭县| 大埔县|