SpringMVC和Hessian配置MethodInterceptor

MethodInterceptor 是通過AOP實現方法級的攔截,常用于打日志,異常攔截等操作。
使用步驟

  1. 創建一個攔截器類實現MethodInterceptor接口
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class CustomMethodInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        // 在這里實現您的邏輯
        System.out.println("Before invoking method: " + methodInvocation.getMethod().getName());
        Object result = methodInvocation.proceed();
        System.out.println("After invoking method: " + methodInvocation.getMethod().getName());
        return result;
    }
}
  1. 在xml中聲明攔截器,并指定應用到的切面
<bean id="customInterceptor" class="com.example.CustomMethodInterceptor" />

<aop:config>
    <aop:advisor advice-ref="customInterceptor" pointcut="execution(* com.example.YourController.*(..))" />
</aop:config>

以上就可以實現Bean的攔截了。
注意:hessian的服務有所不同,因為hessian是通過HessianServiceExporter來暴露服務的,直接用pointcut無法攔截到對應請求。可以通過ProxyFactoryBean代理實現服務實現攔截。

    <bean id="myHessianServiceImpl" class="com.example.impl.MyHessianServiceImpl" /> 
    <bean id="customInterceptor" class="com.example.CustomMethodInterceptor" /> 
    <bean name="/myHessianService" class="org.springframework.remoting.caucho.HessianServiceExporter">
        <property name="service">
            <bean class="org.springframework.aop.framework.ProxyFactoryBean">
                <property name="target" ref="myHessianServiceImpl" />
                <property name="interceptorNames">
                    <list>
                        <value>customInterceptor</value>
                    </list>
                </property>
            </bean>
        </property>
        <property name="serviceInterface" value="com.example.MyHessianService"/>
    </bean>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。