MethodInterceptor 是通過AOP實現方法級的攔截,常用于打日志,異常攔截等操作。
使用步驟
- 創建一個攔截器類實現
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;
}
}
- 在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>