原文位址:http://melin.iteye.com/blog/1339060
很早學習rails的時候,rails在伺服器啟動的時候,通過參數可以切換不同運作環境。也許spring從rails吸取了這樣的功能,從spring3.1就提供了profile功能,友善我們為不同的profile使用不同的bean。能夠想到的應用場景就是資料源的配置,在production profile中,可能通過jndi擷取資料源,而在開發環境中配置jndi比較費事,使用durid配置資料源,項目釋出的時候需要修改資料源的配置,比較麻煩,如果忘記修改就更慘了。 為了解決這樣相關的問題,這裡使用maven profile和maven resource plugin為項目提供profile功能。
spring profile執行個體:
<beans profile="development">
<bean id="dataSource-mysql" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url">
<value>jdbc:mysql://192.168.1.100/druid-test</value>
</property>
<property name="username">
<value>admin</value>
<property name="password">
<value>adminpassword</value>
<property name="initialSize">
<value>1</value>
<property name="maxActive">
<value>20</value>
</bean>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
這裡我主要解決項目中三個應用場景:
1:資源檔案配置,每個環境下的屬性值可能不同
2:日志檔案配置,開發環境下日志隻需要在控制台顯示,而production profile中是需要打到日志檔案中。
3:使用maven切換spring profile。
完成上述功能,最主要是在pom.xml檔案中添加如下一段配置:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
這樣maven搜尋src/main/resources下的所有檔案,替換有類似這樣變量${profiles.active}的值,其中profiles.active中的值是配置pom.xml檔案,如下:
<profiles>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profiles.active>development</profiles.active>
</properties>
</profile>
<id>test</id>
<profiles.active>test</profiles.active>
<id>production</id>
<profiles.active>production</profiles.active>
</profiles>
上面配置三種profile,預設激活development profile。
為了解決資源檔案的問題,我們提供三個資源檔案,命名如下。logback-和.xml中間的值為profiles.active的值。
logback-development.xml
logback-production.xml
logback-test.xml
spring property-placeholder引用資源檔案的方式如下。
<context:property-placeholder location="classpath:/META-INF/res/resource-${profiles.active}.properties" />
為了解決日志檔案的問題,這裡使用了logback,和資源檔案一樣提供四個配置檔案。
在classpath下添加logback.xml。logback預設加載classpath下的logback.xml檔案,配置内容如下:
<configuration>
<include resource="/META-INF/logback/logback-${profiles.active}.xml"/>
</configuration>
激活spring profile,隻要在web.xml中添加如下配置:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${profiles.active}</param-value>
</context-param>