Spring应用程序上下文:访问web.xml的context-params?

15

你好,

有没有办法从web.xml的context-param获取值并传递到Spring上下文中?

例如,我在web.xml中定义了一个值:

<context-param>
  <param-name>compass-index</param-name>
  <param-value>file:///home/compass/index</param-value>
</context-param>

我希望将该值分配给bean属性:

<bean ...>
<props>
  <prop key="compass.engine.connection">
    ${from web.xml context-param?}
  </prop>
</props>
</bean>

提前感谢?

1个回答

25

可以 - ServletContextPropertyPlaceholderConfigurer

这篇文章解释了细节。简单而言,你需要:

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
</bean>

然后像这样使用属性:

<bean ...>
   <property name="compassIndex" value="${compass-index}" />
</bean>

或使用 @Value("${compass-index}")


5
从Spring 3.1开始,ServletContextPropertyPlaceholderConfigurer类已经过时(详见javadoc)。 - Petr Gladkikh
谢谢。请查看http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/context/support/ServletContextPropertyPlaceholderConfigurer.html上的弃用说明。 - Bozho
2
Spring文档中特别“酷”的功能是提到了弃用,但没有提供更新的示例代码。 - Askar Kalykov
@Askar Kalkov,文档并没有很清楚地说明你需要做什么,但最终实际上非常简单。请参考这个答案:https://dev59.com/l2Ij5IYBdhLWcg3wmWG1#21175824 - Pytry
3
这似乎是正确的XML代码,因为ServletContextPropertyPlaceholderConfigurer已经被弃用:<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="environment"><bean class="org.springframework.web.context.support.StandardServletEnvironment" /></property> </bean> - Anthony Hayward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接