java - Web 上下文根是否有内置的 Spring 环境变量?

标签 java spring spring-ws contextpath

我正在使用 Spring Web Services 将服务公开为 Web 服务。在我的 spring 配置 xml 文件中,我有一个 bean,它是 DefaultWsdl11Definition 的一个实例。 locationUri 是需要设置的属性之一。这需要是完全合格的 Uri,但我不想在应用程序从 dev 升级到 uat 再到生产时更改此值。 Spring 知道 Web 应用程序上下文根是什么,那么我可以在配置文件中指定一个变量来访问它吗?

类似:

<bean id="myWebServices"
    class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
    <property name="schemaCollection">
        <bean
            class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
            <property name="xsds" ref="xsdList"/>
            <property name="inline" value="true" />
        </bean>
    </property>
    <property name="portTypeName" value="myWebServices" />
    <property name="locationUri" value="${webContextRoot}/webServices" />
</bean>

最佳答案

使用 Spring 3.0,您应该能够通过 Web 应用程序上下文中的 servletContext bean 访问 servlet 上下文:

<property name="locationUri" value="#{servletContext.contextPath}/webServices" />

如果您使用的是 pre-Spring-EL(3.0 之前),您应该可以这样做

<bean name="servletContextBean" class="org.springframework.web.context.support.ServletContextFactoryBean" />
<bean name="contextPath" factory-bean="servletContextBean" factory-method="getContextPath" />
<bean name="locationUri" factory-bean="contextPath" factory-method="concat">
   <constructor-arg value="/webServices" />
</bean>

在你的 myWebservices bean 中

<property name="locationUri" ref="locationUri" />

编辑:

我不认为从 ServletContext 获取服务器名称和端口,因为根据设置,Web 容器可能不知道主机名(即 HTTP 服务器可能在 Web 容器前面,例如,tomcat 可能在后面Apache Web 服务器或取决于 Websphere 配置)。

但是,以下可能是获取主机名的解决方案的一部分。使用 Spring 3.0,您可以执行以下操作:

<property name="host" 
          class="java.net.InetAddress" 
          factory-method="getLocalHost"/>

<property name="locationUri" 
          value="http://#{host.canonicalHostName}:8080/#{servletContext.contextPath}/webServices" />

关于java - Web 上下文根是否有内置的 Spring 环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6931585/

相关文章:

java - 用 3 个列表填充 GridView

Java 基准测试 - 为什么第二个循环更快?

java - HTTP 请求未委托(delegate)给根 WebApplicationContext 的 Controller

java - spring-security 解耦角色和权限

java - 正确测试 Spring 服务

java - Android USB 主机无法读取和写入 Cp2102SerialDriver 数据

java - 如何在两个实体之间使用 foreach

java - 使用 Spring 4.2 注释和 ActiveMQ 对 @JmsListener 进行身份验证

java - 拦截器中从MessageContext获取ServletContext

java - 如何为 Spring 的 WebServiceTemplate 创建模拟对象?