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

类似于如何从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的末尾。

事实上,最初的问题可能是应该实施的问题。