类似我可以从JAX-WS Web服务中访问ServletContext吗?,有没有办法访问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;
    }
}
有帮助吗?

解决方案

我认为Web服务不应该了解Web或servlet上下文或其应用程序上下文。我不明白为什么它应该知道这些。它不应该更加被动吗?注入它需要的东西并让它完成它的工作。与客户的服务交互应基于预先定义的合同。如果它必须从某种类型的上下文中获取未知值,客户将如何知道需要设置什么或如何设置它?

我会更进一步说,Web服务应该是Spring服务接口的包装器。它只是揭示它的所有可能方式中的另一个选择。您的Web服务应该只执行编组和解组XML请求/响应对象并与Spring服务协作。

其他提示

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;
  ...
}

让你的web服务bean扩展一个spring bean。

我会安装一个Filter,在链接ThreadLocal

之前保存ServletContext

根据SpringBeanAutowiringSupport类的JavaDoc,请参阅: http ://docs.spring.io/autorepo/docs/spring-framework/3.0.x/api/org/springframework/web/context/support/SpringBeanAutowiringSupport.html

阅读注释:在javadoc的末尾。

最初的问题,实际上可能就是应该实施的方式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top