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 阅读(775)
评论(0) 编辑 收藏 所属分类:
Framework