1

我需要根据环境(dev、qa 或 prod)选择属性上下文文件,下面是我的 bean 配置PropertyPlaceholderConfigurer

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:**/config/handsOn-${proj.env}.properties</value>
    </property>
</bean>

那么我怎样才能让spring框架根据它部署的环境来选择正确的文件。

我可以根据部署的主机获取环境。使用下面的代码,

InetAddress.getLocalHost().getHostName()

任何帮助将不胜感激..!!

4

2 回答 2

2

有几种方法可以做到这一点。

  1. 查看 springs 属性注入。您可以在预定义的位置定义属性,并确保正确的属性存在于右侧框 <util:properties location="${path.to.properties.file}"/>
  2. 如果您不想这样做,请考虑将环境类型作为 JVM 参数注入(例如 -Denv.type=PROD)或类似的东西。然后你可以在春天使用这个属性。查看如何在 Spring applicationContext.xml 中读取 JVM 参数以了解如何执行此操作。
于 2012-05-31T23:37:07.453 回答
1

最后,我可以使用 maven 配置文件根据环境打包所需的 .properties。我为 dev、qa 和 prod 使用了不同的配置文件,如下所示,

<profiles>
        <profile>
            <id>dev</id>
            <activation>
              <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>2.4</version>
                        <executions>
                            <execution>
                                <id>copy-dev-resources</id>
                                <phase>process-resources</phase>
                                <goals>
                                    <goal>copy-resources</goal>
                                </goals>
                                <configuration>
                                    <!-- this is important -->
                                    <overwrite>true</overwrite>
                                    <!-- target -->
                                    <outputDirectory>${project.basedir}/WebContent/WEB-INF/config</outputDirectory>
                                    <resources>
                                        <resource>
                                            <!-- source -->
                                            <directory>${project.basedir}/WebContent/WEB-INF/config/dev</directory>
                                        </resource>
                                    </resources>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
</profiles>
于 2012-06-04T01:25:16.450 回答