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