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

          例子:
          系統(tǒng)中已經(jīng)有如下的類:
          接口
          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來完成任務(wù)。
          首先定義接口
          package?cn.blogjava.introduction;

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

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

          }

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

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 保康县| 景东| 木里| 图木舒克市| 南漳县| 江津市| 珠海市| 岑巩县| 手游| 永丰县| 龙口市| 利津县| 桃江县| 邵东县| 嘉禾县| 德惠市| 容城县| 泗洪县| 维西| 枝江市| 阳泉市| 高雄市| 桦川县| 阳城县| 长岛县| 安康市| 丽水市| 昭平县| 松桃| 平顺县| 阜南县| 明溪县| 治县。| 长宁县| 高台县| 芒康县| 波密县| 班戈县| 壤塘县| 樟树市| 长宁区|