使用CXF暴露與調用接口,爲了方便追蹤錯誤,因此想要在接口被調用時將一些運行時數據記錄起來,因此就想到了攔截器。spring
CXF自帶攔截器,可是據我初步瞭解,自帶的攔截器都是通過封裝,用來打印日誌什麼的,好像沒有提供給開發者定製功能的方式(沒有深刻了解,若是有說錯請方便斧正)markdown
其實Spring的攔截器使用挺方便的,實現org.aopalliance.intercept.MethodInterceptor接口中的invoke方法,在方法中實現想要的邏輯。而後在Spring配置文件中注入它就了事。ide
攔截器實現方法日誌
@Override public Object invoke(MethodInvocation invocation) throws Throwable { //獲取當前被調用的方法 Method method = invocation.getMethod(); String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName(); //執行被攔截器攔截下來的方法,得到其返回值 Object object = invocation.proceed(); //作本身的邏輯,我這裏將被調用的方法信息放入返回值中。 if (object instanceof SimpleResult) { SimpleResult result = (SimpleResult) object; result.createMsg(methodName); } return object; }
將攔截器注入IOC容器中code
<bean id="resultLogInterceptor" class="com.elin4it.demo.interceptor.ResultLogInterceptor"/>
配置攔截器接口
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!--配置攔截器名--> <property name="interceptorNames"> <list> <value>resultLogInterceptor</value> </list> </property> <!--要攔截的接口,能夠使用通配符--> <property name="beanNames"> <list> <value>*Facade</value> </list> </property> </bean>