當介面被呼叫時使用Spring攔截器注入執行時資料
阿新 • • 發佈:2019-01-24
開發背景
使用CXF暴露與呼叫介面,為了方便追蹤錯誤,所以想要在介面被呼叫時將一些執行時資料記錄起來,所以就想到了攔截器。
CXF自帶攔截器,但是據我初步瞭解,自帶的攔截器都是經過封裝,用來列印日誌什麼的,好像沒有提供給開發者定製功能的方式(沒有深入瞭解,如果有說錯請方便斧正)
流程
其實Spring的攔截器使用挺方便的,實現org.aopalliance.intercept.MethodInterceptor介面中的invoke方法,在方法中實現想要的邏輯。然後在Spring配置檔案中注入它就了事。
程式碼
攔截器實現方法
@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容器中
<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>