spring 是否可以将 web.xml 中的 .properties 文件与 contextConfigLocation 参数结合使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2515954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:01:41  来源:igfitidea点击:

Is it possible to use .properties files in web.xml in conjunction with contextConfigLocation parameter?

springpropertiesweb.xml

提问by Vladimir

Here is part of my web.xml:

这是我的 web.xml 的一部分:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:application-config.xml
        </param-value>
</context-param>

application-config.xml uses property placeholder:

application-config.xml 使用属性占位符:

<context:property-placeholder location="classpath:properties/db.properties"/>

Is it possible somehow to define which properties file to use in web.xml rather than in application-config.xml?

是否有可能以某种方式定义在 web.xml 而不是 application-config.xml 中使用哪个属性文件?

回答by axtavt

Yes, you can use ServletContextParameterFactoryBeanto expose context-paramvalue (it also requires full form of PropertyPlaceholderConfigurerinstead of simple context:property-placeholder):

是的,您可以使用ServletContextParameterFactoryBean来公开context-param值(它还需要完整形式的PropertyPlaceholderConfigurer而不是简单的context:property-placeholder):

<bean id = "myLocation" class = 
    "org.springframework.web.context.support.ServletContextParameterFactoryBean">
    <property name="initParamName" value = "myParameter" />
</bean>

<bean class = 
    "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" ref = "myLocation" />
</bean>

Or use Spring 3.0's EL:

或者使用 Spring 3.0 的 EL:

<bean class = 
    "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value = "#{contextParameters.myParameter}" />
</bean>

回答by Oliver Drotbohm

Totally agree with axtavt. So all the info combined the most simple solution with Spring 3.0 thus is:

完全同意 axtavt。因此,所有信息将最简单的解决方案与 Spring 3.0 相结合,因此是:

<context:property-placeholder location="#{contextParameters.propertiesLocation}"/>

with

<context-param>
   <param-name>propertiesLocation</param-name>
   <param-value>classpath:properties/db.properties</param-value>
</context-param>

in web.xml.

在 web.xml 中。