如何从JAX-WS Web服务中访问ApplicationContext?

pih*_*agy 9 java spring web-services jax-ws

类似于如何从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;
    }
}
Run Code Online (Sandbox Code Playgroud)

max*_*dim 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;
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • +1感谢您指向我的'SpringBeanAutowiringSupport`方向.我一直在努力让Glassfish放弃对JAX-WS的管理并让Spring接受它.这是一个更容易的解决方案,让Spring专注于它擅长的事情. (2认同)

duf*_*ymo 1

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

我想进一步说,Web 服务应该是 Spring 服务接口的包装器。这只是所有可能的揭露方式中的又一种选择。您的 Web 服务应该只做编组和解组 XML 请求/响应对象并与 Spring 服务协作。