不要在代码中添加逻辑来测试您在哪个环境中运行-这是灾难的根源(或者至少在路上燃烧了大量的午夜石油)。
您使用Spring,因此要利用它。使用依赖注入为代码提供特定于环境的参数。例如,如果您需要在测试和生产中调用具有不同终结点的Web服务,请执行以下操作:
public class ServiceFacade { private String endpoint; public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public void doStuffWithWebService() { // use the value of endpoint to construct client }}接下来,使用Spring的PropertyPlaceholderConfigurer(或PropertyOverrideConfigurer)从.properties文件或JVM系统属性填充此属性,如下所示:
<bean id="serviceFacade" > <property name="endpoint" value="${env.endpoint}"/></bean><bean > <property name="locations"> <value>classpath:environment.properties</value> </property></bean>现在像这样创建两个(或三个或四个)文件-每个用于不同的环境。
在environment-dev.properties中:
env.endpoint=http://dev-server:8080/
在environment-test.properties中:
env.endpoint=http://test-server:8080/
现在,为每个环境获取适当的属性文件,将其重命名为environment.properties,然后将其复制到应用程序服务器的lib目录或其他将出现在应用程序的类路径中的位置。例如,对于Tomcat:
cp environment-dev.properties $CATALINA_HOME/lib/environment.properties
现在部署您的应用程序-在运行时设置端点属性时,Spring将替换值“ http:// dev-server:8080 /”。
有关如何加载属性值的更多详细信息,请参见Spring文档。



