我爱熊猫

最新评论

spring aop 之一传统方式2

上一篇的监听器是前置监听器,接下来看后置监听器的实现。

其它代码不变,在spring 配置中加入:

<bean id="logAdvisorAfter" class="cn.com.ultrapower.advice.ordinary.LogAdvisorAfter" />

然后在helloAction bean的interceptorNames中增加(即前文说的list,可以再增加多个的地方):

<value>logAdvisorAfter</value>

LogAdvisorAfter的代码:

public class LogAdvisorAfter implements AfterReturningAdvice {
/**
* returnValue - the value returned by the method, if any
* method - method being invoked
* args - arguments to the method
* target - target of the method invocation. May be null
*/
@Override
public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
System.out.println("Log:do something after call");
System.out.println("Log:call method name:"+method.getName());
HelloActionImpl action = (HelloActionImpl) target ;
System.out.println("Log:action name:"+action.getName());

}

}

这里的afterReturning方法会在action.sayHello()方法后执行。并且这里还可以获取action实例的属性name(action中新增了个name属性,并且添加了get/set方法)。

接下来再看拦截器的实现:

<!--改变访问-->

<bean id="changeInterceptor" class="cn.com.ultrapower.advice.ordinary.ChangeSayInterceptor" />

...

helloAction的interceptorNames中增加
<value>changeInterceptor</value>

ChangeSayInterceptor的代码:

public class ChangeSayInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation i) throws Throwable {
boolean ret = true ;
/*
* 拦截访问
*/
System.out.println("Log:do something on the call");
System.out.println("Log:call method name:"+i.getMethod().getName());
/*
* 执行访问的方法
*/
//注释掉下面2行代码后,action.sayHello()就不会执行了
ret = i.proceed();
System.out.println("Log:method:" + i.getMethod() + " returns :" + ret);
return ret;
}
}
这里的invoke方法会拦截原有的方法,使用MethodInvocation .proceed()继续执行.很显然的是,可以在方法执行前加代码,和方法执行后加代码.并且还可以直接屏蔽掉原有方法的执行(即注释掉i.proceed()).

可以更加充分的利用该功能,直接切换代码的运行:


// 不再say Hello ,改 say welcome
/*
* 注意:原方法有返回值,切换后一定要正确设定返回值
*/
try {
HelloActionImpl action = (HelloActionImpl) i.getThis();
System.out.println("Welcome!" + action.getName());
} catch (Exception e) {
ret = false ;
}
return ret;


posted on 2008-06-07 16:19 flyoo 阅读(82) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
博客园   IT新闻   Chat2DB   C++博客   博问