spring为beans标签提供了profile功能,以便项目的开发和生成环境分离。
<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。
切换profile可以写在web.xml里面:
<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 就是发布生产版本。
然后我们需要在项目里面src resource里面的某个配置文件添加如:
profile.active=${profile.active}
这样maven在编译时会自动设置profile。最后就是设法让spring能够读取到我们的配置。我们的做法是自己实现ContextLoaderListener,里面读取这个properties文件,将spring profiles属性设置为我们需要的值。
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, activeProfile);
来源:oschina
链接:https://my.oschina.net/u/918405/blog/113755