我有一个像这样的PropertyPlaceholderConfigurer:
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:assuredlabor/margarita-${runningMode}.properties</value>
</list>
</property>
</bean>
我希望能够在web.xml中指定我的运行模式,如下所示:
<context-param>
<param-name>runningMode</param-name>
<param-value>production</param-value>
</context-param>
所以我把这个bean放在上面描述的'main'属性bean上面了:
<bean id="servletPropertyPlaceholderConfigurer" class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
</bean>
但这似乎不起作用。
春天有可能吗?我现在正在使用2.5版。
我发现了类似的问题:
PropertyPlaceholderConfigurer with Tomcat & ContextLoaderListener
但是没有讨论ServletContextPropertyPlaceholderConfigurer,所以我认为这是一个合理的问题。
答案 0 :(得分:1)
来自source code:
PropertyPlaceholderConfigurer的子类,它将占位符解析为ServletContext init参数(即web.xml context-param条目)。
除了web.xml context-params之外,还可以与“locations”和/或“properties”值结合使用。或者,可以在没有本地属性的情况下定义,将所有占位符解析为web.xml context-params(或JVM系统属性)。
如果无法根据应用程序中提供的本地属性解析占位符,则此配置程序将回退到ServletContext参数。也可以配置为让ServletContext init参数覆盖本地属性(contextOverride = true)。
可选择支持搜索ServletContext属性:如果启用,则无法解析的占位符将与相应的ServletContext属性匹配,如果找到则使用其字符串化值。这可用于将动态值提供给Spring的占位符分辨率。
如果未在WebApplicationContext(或任何其他能够满足ServletContextAware回调的上下文)中运行,则此类的行为类似于默认的PropertyPlaceholderConfigurer。这允许在测试套件中保留ServletContextPropertyPlaceholderConfigurer定义。
据我了解,这意味着您只能使用一个配置器:
<bean id="propertyPlaceholderConfigurer" class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:assuredlabor/margarita-${runningMode}.properties</value>
</list>
</property>
</bean>
答案 1 :(得分:1)
你不能在春天2做到这一点,没有一些我不认为的自定义编码,因为一个属性占位符不能配置另一个。
您需要使用弹簧3来开箱即用。要实现这一点,您必须创建一个以某种方式具有所需值的bean,并在设置属性占位符时使用spring-el引用该spring。有一个特殊的bean用于获取单个servlet上下文参数,如下所示:
<bean id="runningMode" class="org.springframework.web.context.support.ServletContextAttributeFactoryBean">
<property name="attributeName" value="runningMode" />
</bean>
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:assuredlabor/margarita-#{runningMode}.properties</value>
</list>
</property>
</bean>
然后你可以引用普通$ {}语法中的任何属性