使用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>
僅就實現配置文件切換來說,兩種方式中我傾向於后者,更簡潔明了。當然前者有些功能是后者無法實現的,比如針對不同的環境有選擇性的實例化對象。
