在applicationContext.xml中添加下邊的內容:web
<beans profile="develop"> <context:property-placeholder location="classpath*:jdbc-develop.properties"/> </beans> <beans profile="production"> <context:property-placeholder location="classpath*:jdbc-production.properties"/> </beans> <beans profile="test"> <context:property-placeholder location="classpath*:jdbc-test.properties"/> </beans>
profile的定義必定要在文檔的最下邊,不然會有異常redis
能夠直接在bean裏進行定義一些特殊的屬性,以下邊這樣,在test,初始化數據庫與默認數據。(代碼摘錄:springside)spring
<!-- unit test環境 --> <beans profile="test"> <context:property-placeholder ignore-resource-not-found="true" location="classpath*:/application.properties, classpath*:/application.test.properties" /> <!-- Simple鏈接池 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 初始化數據表結構 與默認數據--> <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL"> <jdbc:script location="classpath:sql/h2/schema.sql" /> <jdbc:script location="classpath:data/import-data.sql" encoding="UTF-8"/> </jdbc:initialize-database> </beans>
在web.xml中添加一個context-param來切換當前環境:sql
<context-param> <param-name>spring.profiles.active</param-name> <param-value>develop</param-value> </context-param>
若是是測試類可使用註解來切換:數據庫
@RunWith(SpringJUnit4ClassRunner.class) app
@ContextConfiguration(locations = "classpath:applicationContext.xml") ide
@ActiveProfiles("test") 測試
public class ServiceTest extends AbstractTransactionalJUnit4SpringContextTests url
能夠寫一個基類,而後都繼承該類,這樣很方便。spa
或者還有一種方式:
applicationcontext-xml:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:locations-ref="locations"/> <beans profile="production"> <util:list id="locations"> <value>classpath:/properties/production/sys_addr.properties</value> <value>classpath:/properties/production/redis.properties</value> <value>classpath:/properties/production/jdbc.properties</value> </util:list> </beans> <beans profile="test"> <util:list id="locations"> <value>classpath:/properties/test/sys_addr.properties</value> <value>classpath:/properties/test/redis.properties</value> <value>classpath:/properties/test/jdbc.properties</value> </util:list> </beans>