MethodInterceptor 是通過AOP實現(xiàn)方法級的攔截髓霞,常用于打日志卦睹,異常攔截等操作。
使用步驟
- 創(chuàng)建一個攔截器類實現(xiàn)
MethodInterceptor
接口
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class CustomMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
// 在這里實現(xiàn)您的邏輯
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>
以上就可以實現(xiàn)Bean的攔截了。
注意:hessian的服務有所不同障斋,因為hessian是通過HessianServiceExporter
來暴露服務的纵潦,直接用pointcut無法攔截到對應請求±罚可以通過ProxyFactoryBean
代理實現(xiàn)服務實現(xiàn)攔截邀层。
<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>