基于 Spring 的 Web 应用程序的特定环境配置?
2022-09-03 04:31:08
						我如何知道Web应用程序的部署环境,例如它是本地的,dev的,qa还是prod等。有没有办法在运行时在spring应用程序上下文文件中确定这一点?
我如何知道Web应用程序的部署环境,例如它是本地的,dev的,qa还是prod等。有没有办法在运行时在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(或者属性OverrideConfigurer)从.properties文件或JVM系统属性填充此属性,如下所示:
<bean id="serviceFacade" class="ServiceFacade">
    <property name="endpoint" value="${env.endpoint}"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:environment.properties</value>
    </property>
</bean>
现在创建两个(或三个,或四个)文件,如下所示 - 每个不同的环境一个。
在环境开发属性中:
env.endpoint=http://dev-server:8080/
在 environment-test.properties 中:
env.endpoint=http://test-server:8080/
现在,为每个环境获取适当的属性文件,将其重命名为环境属性,然后将其复制到应用服务器的 lib 目录或它将出现在应用类路径上的其他位置。例如,对于雄猫:
cp environment-dev.properties $CATALINA_HOME/lib/environment.properties
现在部署你的应用 - Spring 将在运行时设置终结点属性时替换值“http://dev-server:8080/”。
有关如何加载属性值的更多详细信息,请参阅 Spring 文档。
 
				    		 
				    		 
				    		 
				    		