能否在web.xml中与contextConfigLocation参数一起使用.properties文件?

3

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

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

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

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

有没有办法在web.xml中定义要使用的属性文件,而不是在application-config.xml中定义?

1
你是怎么在web.xml中获取db.properties文件的?我尝试使用${property.name},但它不起作用。 - Ani
2个回答

4

是的,您可以使用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>

或者使用Spring 3.0的EL:

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

6
如果你们能澄清这个答案,我相信它会对很多人有帮助。 - euther

4
完全同意axtavt的观点。因此,将所有信息与Spring 3.0结合使用的最简单解决方案即为:
<context:property-placeholder location="#{contextParameters.propertiesLocation}"/>

使用

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

在 web.xml 文件中。

那么,这就足以从db.properties文件中读取属性,并通过${yaddayadda}在applicationContext.xml和web.xml中使用它们了吗? - Tuukka Mustonen
1
@Oliver: 正如你上面提到的,需要在web.xml中读取config.properties,并在web.xml的指定上下文参数和app.xml的上下文属性中进行设置..可以使用<param-value>${SystemInfo}</param-value>作为初始化参数在web.xml中,但它没有显示值,而是显示${SystemInfo}。 - TP_JAVA
你好。还需要什么才能让它工作?当我这样做时,我会得到Could not open ServletContext resource [/#{contextParameters.propertiesLocation}]的错误提示。 - thedarklord47

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