基于Spring的Web应用程序的特定于环境的配置?

Rit*_*esh 16 java deployment spring spring-mvc java-ee

我如何知道Web应用程序的部署环境,例如它是本地的,dev,qa还是prod等.有什么方法可以在运行时在spring应用程序上下文文件中确定这个?

Pav*_*vel 25

不要在代码中添加逻辑来测试你正在运行的环境 - 这是一个灾难的处方(或者至少在路上燃烧很多午夜油).

你使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来,使用Spring的PropertyPlaceholderConfigurer(或者PropertyOverrideConfigurer)从.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>
Run Code Online (Sandbox Code Playgroud)

现在创建两个(或三个或四个)文件,如下所示 - 每个文件对应一个不同的环境.

在environment-dev.properties中:

env.endpoint=http://dev-server:8080/
Run Code Online (Sandbox Code Playgroud)

在environment-test.properties中:

env.endpoint=http://test-server:8080/
Run Code Online (Sandbox Code Playgroud)

现在为每个环境获取相应的属性文件,将其重命名为environment.properties,然后将其复制到应用服务器的lib目录或应用程序类路径中显示的其他位置.例如Tomcat:

cp environment-dev.properties $CATALINA_HOME/lib/environment.properties
Run Code Online (Sandbox Code Playgroud)

现在部署你的应用程序 - 当它在运行时设置你的端点属性时,Spring将替换值"http:// dev-server:8080 /".

有关如何加载属性值的更多详细信息,请参阅Spring文档.


Amr*_*afa 10

值得注意的是,Spring 3.1 M1引入了配置文件支持.这可能是满足这种需求的最终答案.所以要留意它.

与此同时,我个人完全正是帕维尔所描述的.