spring爲beans標籤提供了profile功能,以便項目的開發和生成環境分離。 java
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <beans profile="dev,test"> <context:property-placeholder location="classpath:application.properties" /> <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"> <property name="driverClass" value="${db.driver}"/> <property name="jdbcUrl" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> <property name="idleConnectionTestPeriodInMinutes" value="60"/> <property name="idleMaxAgeInMinutes" value="240"/> <property name="maxConnectionsPerPartition" value="30"/> <property name="minConnectionsPerPartition" value="10"/> <property name="partitionCount" value="3"/> <property name="acquireIncrement" value="5"/> <property name="statementsCacheSize" value="100"/> <property name="releaseHelperThreads" value="3"/> </bean> <beans profile="production"> <context:property-placeholder ignore-resource-not-found="true" location="classpath:application.properties,classpath:application-production.properties" /> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${db.jndi}"/> </bean> </beans> </beans>
以數據庫爲例,開發環境使用的是直接將配置寫在項目的配置文件裏面,而生產環境則使用了jndi。 web
切換profile能夠寫在web.xml裏面: spring
<context-param> <param-name>spring.profiles.active</param-name> <param-value>dev</param-value> </context-param>
不過得改web.xml,如今通常項目都使用maven來管理,maven也有profile,能夠將它們結合起來。 數據庫
<properties> <profile.active>dev</profile.active> </properties> <build> <defaultGoal>install</defaultGoal> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.properties</include> </includes> </resource> </resources> </build> ... <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> </profile> <profile> <id>production</id> <properties> <profile.active>production</profile.active> <profile.scope>provided</profile.scope> </properties> </profile> </profiles
mvn install -Pproduction 就是發佈生產版本。 app
而後咱們須要在項目裏面src resource裏面的某個配置文件添加如: maven
profile.active=${profile.active}
這樣maven在編譯時會自動設置profile。最後就是設法讓spring可以讀取到咱們的配置。咱們的作法是本身實現ContextLoaderListener,裏面讀取這個properties文件,將spring profiles屬性設置爲咱們須要的值。 ide
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, activeProfile);