introduction為對象動態的加入原先所沒有的職責。

          例子:
          系統中已經有如下的類:
          接口
          package?cn.blogjava.introduction;

          public?interface?ISome?{
          ????
          public?void?doSome();
          }

          package?cn.blogjava.introduction;

          public?class?Some?implements?ISome?{

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

          ????}

          }

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

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

          實現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);
          ????}

          }

          測試類:
          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) 評論(0)  編輯  收藏 所屬分類: Framework

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 长宁区| 汪清县| 昔阳县| 大方县| 汉川市| 南皮县| 城口县| 从江县| 三原县| 宜昌市| 大化| 鄂伦春自治旗| 桐城市| 疏勒县| 门头沟区| 谷城县| 汉川市| 建宁县| 武城县| 盱眙县| 广平县| 南通市| 滦平县| 延边| 修水县| 麻阳| 龙泉市| 化隆| 灵山县| 双辽市| 都匀市| 大城县| 禹州市| 永平县| 蒲江县| 临潭县| 鱼台县| 淳化县| 山阳县| 富顺县| 静宁县|