2017-09-07 82 views
0

我使用spring實現了一些其他的web服務。 我有一些常見的代碼,我需要在每個Web服務之前執行。 Crrently我明確地在每個Web服務的開始調用這個通用代碼。如何在執行Spring web服務之前運行一些代碼

有沒有辦法在調用Web服務之前讓spring「自動」調用這個公共代碼?

+1

你能「調用Web服務之前」定義?你是指一些配置步驟(初始化池,加載/準備資源和映射,構建引用表等),或者你的意思是在每次調用服務之前應該處理的事情(認證,審計日誌記錄,會話初始化,等等。)? – user2478398

+0

你有沒有試過任何代碼?你可以發佈他們的更清晰的場景?! –

+0

我需要保存請求信息,(瀏覽器,IP地址和操作系統版本),我需要訪問httpRequest對象來做到這一點,而不是與每個Web服務手動執行此操作,我問是否有任何支持春天這樣做。 –

回答

0

你應該使用Spring AOP的攔截每一個Web服務,並執行it.Like通用代碼下面的代碼:

<bean id="aspect" class="com.zhuyiren.Aspect"/> 

<aop:config> 
    <aop:aspect ref="aspect"> 
     <aop:before method="before" pointcut="execution(* com.zhuyiren.service..*.*(..))"/> 
    </aop:aspect> 
</aop:config> 

這上面的代碼意味着調用一些豆在com.zhuyiren.service包裝的每一個方法始終執行該方法在commoncom.zhuyiren.Aspect。您可以在common method.Like寫共用代碼:

public void common(){ 
    System.out.println("execute some common code"); 
} 

測試用例:

public static void main(String[] args) throws Exception { 
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test.xml"); 
    UserService service = context.getBean(UserService.class); 
    System.out.println(service.getUser(3)); 
} 

打印是:

execute some common code 
UserInfo{id=3, name='zhuyiren', password='123456', testString=[]} 
0

看看HandlerInterceptorAdapter 你可以擴展它,並從請求中提取任何您需要的信息

最佳

相關問題