spring 笔记3: Spring 多环境配置文件切换

使用Spring进行开发时,需要面对不同的运行环境,比如开发环境、测试环境、生产环境等。大多时候不同的环境需要不同的配置文件。网上很多资料都是使用Spring的Bean definition profiles 功能来实现(https://docs.spring.io/spring/docs/4.2.4.RELEASE/spring-framework-reference/html/beans.html#beans-definition-profiles)。这种方式就会出现同一个Bean要正对不同的环境分别声明,即繁琐,又造成相同的配置要重复很多遍。

比如:需要在vmoption 里面增加 -Dspring.profiles.active=dev

   

    <beans profile="dev">
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath*:properties/config_dev.properties</value>
                </list>
            </property>
        </bean>
 
    </beans>
    <beans profile="test">
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath*:properties/config_test.properties</value>
                </list>
            </property>
        </bean>
    
    </beans>
    <beans profile="uat">
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath*:properties/config_uat.properties</value>
                </list>
            </property>
        </bean>

    </beans>
    <beans profile="product">
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath*:properties/config_product.properties</value>
                </list>
            </property>
        </bean>
  
    </beans>

 

相比之下,我更喜欢这种方式:

需要vm option里面新增:-Denv=_rel。 如果没有新增属性,那么默认加载的是文件mybatis/jdbc.properties 。 

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:mybatis/jdbc${env:}.properties</value>
                <value>classpath*:cache/radis${env:}.properties</value>
                <value>classpath*:applicationConfig${env:}.properties</value>
                <value>classpath*:rabbitmq/rabbitmq${env:}.properties</value>
                <value>classpath*:redisson/redisson${env:}.properties</value>
                <value>classpath*:webservice/webservice.properties</value>
                <value>classpath*:apiclient${env:}.properties</value>
                <value>classpath*:httprequest${env:}.properties</value>

            </list>
        </property>
    </bean>

仅就实现配置文件切换来说,两种方式中我倾向于后者,更简洁明了。当然前者有些功能是后者无法实现的,比如针对不同的环境有选择性的实例化对象。

 

posted @ 2018-10-18 18:24  孤独流星  阅读(2512)  评论(0编辑  收藏  举报