2009-03-02 30 views
9

How can I access the ServletContext from within a JAX-WS web service?類似,有沒有辦法訪問applicationContext,比這更容易?如何從JAX-WS Web服務中訪問ApplicationContext?

import javax.annotation.Resource; 
import javax.jws.WebService; 
import javax.servlet.ServletContext; 
import javax.xml.ws.WebServiceContext; 
import javax.xml.ws.handler.MessageContext; 

import org.springframework.web.context.WebApplicationContext; 
import org.springframework.web.context.support.WebApplicationContextUtils; 

@WebService 
public class MyWebService { 
    // boilerplate code begins :(

    @Resource 
    private WebServiceContext context; 
    private WebApplicationContext webApplicationContext = null; 

    /** 
    * @return 
    * @throws IllegalStateException 
    */ 
    private WebApplicationContext getWebApplicationContext() 
      throws IllegalStateException { 
     if (webApplicationContext != null) 
      return webApplicationContext; 
     ServletContext servletContext = 
       (ServletContext) context.getMessageContext().get(
         MessageContext.SERVLET_CONTEXT); 
     webApplicationContext = 
       WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); 
     return webApplicationContext; 
    } 
} 

回答

1

鏈接我不認爲Web服務應該瞭解網絡或servlet上下文或應用上下文之前保存ServletContext的一個過濾器。我不明白爲什麼它應該知道這些。它不應該更加被動嗎?注入需要的東西並讓它做好工作。與客戶的服務交互應該基於預先定義的合同。如果必須從某種情況下獲得未知值,客戶將如何知道需要設置什麼或如何設置?

我想進一步說,一個Web服務應該是一個Spring服務接口的包裝。這只是揭示它的所有可能方式中的一個更多選擇。您的Web服務應該做的不過是編組和解組XML請求/響應對象,並與Spring服務協作。

+0

那麼,我該如何與Spring服務協作,如果我不能說:appContext.getBean('myBean')? – pihentagy 2009-03-03 11:08:05

+0

通過setter或構造函數注入它。依賴注入意味着「不要打電話給我們,我們會打電話給你。」你的對象不必擁有應用上下文來獲得他們需要的東西。 – duffymo 2009-03-03 13:47:13

0

我會安裝在一個ThreadLocal

1

使您的Web服務bean擴展Spring bean。

this

8
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.web.context.support.SpringBeanAutowiringSupport; 


@WebService( 
    endpointInterface = "Bla", 
    targetNamespace = "http://bla/v001", 
    wsdlLocation = "WEB-INF/wsdl/bla.wsdl",  
    serviceName = "BlaService", 
    portName = "BlaPort") 
public class BlaWs extends SpringBeanAutowiringSupport implements BlaPort { 

    @Autowired 
    @Qualifier("dao") 
    private Dao dao; 
    ... 
}