在Spring中读取jar中存在的配置文件

时间:2011-01-31 16:05:47

标签: java spring

问候!

我有一个spring应用程序,它取决于传统的spring应用程序,以jar形式发布。请注意,传统jar在jar本身内部有spring配置文件。那么有两个属性文件:app.properties和override.properties。

现在从外部项目中,我可以使用类似的东西读取一个配置属性:

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

<bean name="propertyResource" class="org.springframework.core.io.ClassPathResource">
  <constructor-arg><value>spring-config.properties</value></constructor-arg>
 </bean> 

但我无法使其适用于2个属性文件。有人遇到类似问题并找到出路吗?请建议。我尝试使用list propertyResource bean,有两个PropertyPlaceholderConfigurer bean,但没有用。

顺便说一句,仅仅是为了记录,我已经搜索过(但不是彻底)弹簧文档,所以这将是我将要做的下一件事,但如果有人已经知道解决方案,为什么要重新发明轮子。 / p>

2 个答案:

答案 0 :(得分:3)

如果我理解正确,您正在尝试将多个属性文件加载到PropertyPlaceholderConfigurer中。您可以通过设置'locations'属性而不是'location'属性来实现此目的。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:app.properties</value>
            <value>classpath:override.properties</value>
        </list>
    </property>
</bean>

答案 1 :(得分:2)

您只需忽略无法解析的占位符属性:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" ref="propertyResource"></property>
  <property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

几点说明:

查看p namespace(注意:此链接已旧但仍然相关),用于速记配置。您的配置将变为:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
        p:ignoreUnresolvablePlaceholders="true" 
        p:locations="classpath:spring-config.properties" />

另请查看context namespace(第c.2.8节)。您的配置将变为:

<context:property-placeholder locations="classpath:spring-config.properties" ignore-unresolvable=true"/>