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

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


          網站導航:
           
          主站蜘蛛池模板: 珠海市| 民勤县| 建昌县| 漳州市| 萍乡市| 阳西县| 南安市| 治县。| 炎陵县| 洛扎县| 镇坪县| 盐亭县| 茌平县| 龙泉市| 怀来县| 南溪县| 郴州市| 东宁县| 乃东县| 沛县| 香格里拉县| 大冶市| 容城县| 崇州市| 武强县| 洛宁县| 改则县| 枣强县| 武夷山市| 大关县| 辽中县| 商河县| 东方市| 大邑县| 左贡县| 南投县| 巨鹿县| 二手房| 北川| 乐都县| 施甸县|