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

Gre*_*reg 12 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>
Run Code Online (Sandbox Code Playgroud)

ben*_*y23 9

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

<property name="locationUri" value="#{servletContext.contextPath}/webServices" />
Run Code Online (Sandbox Code Playgroud)

如果您使用的是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>
Run Code Online (Sandbox Code Playgroud)

在myWebservices bean中

<property name="locationUri" ref="locationUri" />
Run Code Online (Sandbox Code Playgroud)

编辑:

我不认为从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" />
Run Code Online (Sandbox Code Playgroud)


Eug*_*hov -1

您可以将 ApplicationContextAware 接口添加到您的 bean,将其转换为 WebApplicationContext,然后获取 ServletContext。另请参阅类 org.springframework.web.context.ContextLoader