S2Container框架学习笔记之三

来源:互联网 发布:软件就业形势 编辑:程序博客网 时间:2024/06/01 09:55

1. S2container的AOP——S2AOP

S2container是一个支持AOP的框架。它的AOP模块就是S2AOP.

S2AOP默认提供如下一些Interceptor

(1)TraceInterceptor

用于跟踪的Interceptor。要使用Interceptor,就在组件的component配置里指定。例如要在组件Date的getTime方法里使用TraceInterceptor,可以如下配置

<component class="java.util.Date">    <aspect pointcut="getTime">        <component class="org.seasar.framework.aop.interceptors.TraceInterceptor"/>    </aspect></component>

(2)ThrowsInterceptor

捕获例外时的共通处理。使用时继承ThrowsInterceptor,实现Object handleThrowable(Throwable, MethodInvocation),

其中参数Throwable可以指定为Throwable的任意子类。一个Interceptor里可以定义多个handleThrowable()。

例如,要在捕获NullPointerException的时候输出message,可以创建一个如下的Interceptor。

package examples.aaa.interceptor;import org.aopalliance.intercept.MethodInvocation;import org.seasar.framework.aop.interceptors.ThrowsInterceptor;public class MyThrowableInterceptor extends ThrowsInterceptor {    public void handleThrowable(NullPointerException e, MethodInvocation invocation)        throws Throwable {        System.out.println("ぬるぽ");        throw e;    }}

(3)ToStringInterceptor

(4)RemoveSessionInterceptor

当方法正常结束时,从session里移除指定的数据。需要在方法里加RemoveSession注解。例:

@RemoveSession("foo")public void hoge() {    ...}
(5)InvalidateSessionInterceptor
方法正常结束时,销毁session对象。需要在方法里加InvalidateSession注解。例:

@InvalidateSessionpublic void hoge() {    ...}
(6)DependencyLookupInterceptor
(7)InterceptorChain

多个Interceptor可以组合成InterceptorChain,然后需要使用的组件只要指定这个InterceptorChain就OK了。

Interceptor链的配置如下:

<component name="interceptor1" .../><component name="interceptor2" .../><component name="interceptor3" .../><component name="chain" class="org.seasar.framework.aop.interceptors.InterceptorChain">    <initMethod name="add"><arg>interceptor1</arg></initMethod>    <initMethod name="add"><arg>interceptor2</arg></initMethod>    <initMethod name="add"><arg>interceptor3</arg></initMethod></component><component ...>    <aspect>chain</aspect></component><component ...>    <aspect>chain</aspect></component>
(8)InterceptorLifecycleAdapter


自定义Interceptor

自定义Interceptor的话,实现MethodInterceptor接口或继承AbstractInterceptor抽象类。

无论哪个都是要实现invoke()方法:public Object invoke(MethodInvocation invocation) throws Throwable
其中AbstractInterceptor是实现了MethodInterceptor接口的抽象类。 

通过AbstractInterceptor.getTargetClass()能知道调用Interceptor的class。
MethodInvocation类的getThis()、getMethod()、getArguments()方法, 可以以対象的形式取得调用Interceptor的对象、方法、方法参数。 

getThis()取到的类名是类名的字节数组。 调用proceed()就是执行真正的业务方法(配置实现Interceptor的方法)。
以下的例子就是在实际方法的执行前后输出log:

package examples.aaa.interceptor;import org.aopalliance.intercept.MethodInvocation;import org.seasar.framework.aop.interceptors.AbstractInterceptor;public class MyInterceptor extends AbstractInterceptor{    public Object invoke(MethodInvocation invocation) throws Throwable {        System.out.println("before");        Object ret = invocation.proceed();        System.out.println("after");        return ret;    }}





原创粉丝点击