分类:
2008-10-17 13:49:32
public interface CheckInterface {
public abstract void check(String name);
public abstract void excute(String name);
}
好了,下面做一个通知类(Advice):
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
public class BeforeAdvisor implements MethodBeforeAdvice {
private static Logger logger=Logger.getLogger(BeforeAdvisor.class);
public void before(Method m, Object[] args, Object target) throws Throwable {
if (target instanceof CheckInterface){
logger.debug("Is Instanceof CheckInterface!!!");
CheckInterface ci=(CheckInterface)target;
ci.check((String)args[0]);
}
}
}
其中重要的before方法的参数:Object target传入的通知的对象(即测试类的接口),Method m, Object[] args分别是该对象被调用的方法和参数。我们再来作spring bean定义xml文件:
这个定义文件指明了ExcuteClass为监视对象,它的excute方法被执行的时候,BeforeAdvisor将被调用。
最后是测试类:
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringTestCase2 extends TestCase {
CheckInterface test=null;
protected void setUp() throws Exception {
super.setUp();
ApplicationContext ctx=new FileSystemXmlApplicationContext("src/com/wysm/netstar/test/springaop/aoptest.xml");
test = (CheckInterface) ctx.getBean("myCheckClass");
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testExcute(){
test.excute("supervisor");
}
}