【问题标题】:deployment for different environments with maven and spring使用 maven 和 spring 部署不同环境
【发布时间】:2012-08-07 16:20:50
【问题描述】:

我有两个属性文件:

environment.properties:
 - project.host.db3.database.name=oracle

application.properties:
 - database.name=${project.host.db3.database.name}

第一个代表环境变量,第二个代表要在spring项目中使用的属性,在这个配置中我尝试设置 environment.properties 但当然它不起作用:

<bean id="systemPropertiesLoader"   
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" value="#{@systemProperties}" />
        <property name="targetMethod" value="putAll" />
        <property name="arguments">
    <util:properties location="classpath:environment.properties" />
</property>
</bean>

<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
depends-on="systemPropertiesLoader">
<property name="locations">
    <list>
        <value>classpath:application.properties</value>
    </list>
</property>

<!-- bean using database.name -->

可行吗?如果不可行,人们如何在他们的项目中拥有不可知的属性(如 database.name),并且只部署一个文件(war、jar 等)?

【问题讨论】:

  • 为什么不能直接使用 environment.properties 呢?
  • @yorkw,我开始使用自己的属性,后来才知道我应该从另一个属性文件中提供它们,但我仍然认为我应该将我的属性名称与环境属性隔离

标签: spring maven deployment


【解决方案1】:

好吧,只要你像这样定义你的属性,它似乎对于定义的 beans xml 是可行的:

<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
depends-on="systemPropertiesLoader">

但是,如果您曾经尝试从 servlet 访问属性:

this.getClass().getClassLoader().getResourceAsStream("application.properties");

你有机会得到这个:

bad port configuration: ${project.host.db3.database.port}
java.lang.NumberFormatException: For input string: "${project.host.db3.database.port}"

作为对 yorkw 的回答,现在我可以在多个环境中部署相同的战争,并使用 -Denvironment=development 配置主机,因此我可以部署用于开发、生产等的属性文件,并且只需使用:

<bean id="systemPropertiesLoader"   
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" value="#{@systemProperties}" />
        <property name="targetMethod" value="putAll" />
        <property name="arguments">
    <util:properties location="classpath:**${environment}/**environment.properties" />
</property>
</bean>

否则我应该在部署每个环境之前替换 application.properties。我相信还有比这更好的解决方案。

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2017-08-23
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多