spring 筆記3: Spring 多環境配置檔案切換
阿新 • • 發佈:2018-11-10
使用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>
僅就實現配置檔案切換來說,兩種方式中我傾向於後者,更簡潔明瞭。當然前者有些功能是後者無法實現的,比如針對不同的環境有選擇性的例項化物件。