版權聲明:本文首發 http://asing1elife.com ,轉載請注明出處。 https://blog.csdn.net/asing1elife/article/details/82696838
SpringMVC多環境配置
SpringMVC 可以使用 Spring 本身提供的 profile 特性對多環境配置檔案進行統一內建,自動切換
更多精彩
- 更多技術部落格,請移步 asing1elife’s blog
存在的必要
- 日常開發中,一般都存在多個環境,開發、測試、生産
- 上述環境對應的資料庫及配置檔案都會存在不同,是以為項目內建多環境配置很有必要
實作方式
- 內建方式有多種,網上介紹的大多是使用
去區分不同的<beans profile="dev">
檔案*.properties
- 還可以使用
進行不同環境代碼加載@Profile
- 本文介紹的是使用
直接在同一個 xml 檔案中區分不同環境需要的不同配置項<beans profile="dev">
XML配置
- 注意如果使用了多環境的配置的 xml 檔案中存在其他公有屬性,這些屬性需要放在最前面,否則會報錯
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<description>spring-data-redis-cluster</description>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}"/>
<property name="maxTotal" value="${redis.pool.maxActive}"/>
<property name="maxWaitMillis" value="${redis.pool.maxWait}"/>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
</bean>
...
<beans profile="dev">
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.server.url}"/>
<constructor-arg index="2" value="${redis.server.port}" type="int"/>
<constructor-arg index="3" value="${redis.server.timeout}" type="int"/>
<constructor-arg index="4" value="${redis.server.password}"/>
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.server.url}"/>
<property name="port" value="${redis.server.port}"/>
<property name="password" value="${redis.server.password}"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
</bean>
</beans>
<beans profile="prod">
<bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
...
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg ref="redisClusterConfiguration"/>
<constructor-arg ref="jedisPoolConfig"/>
</bean>
</beans>
</beans>
開發環境啟動方式
- IDEA 需要在啟動時添加腳本
以確定使用開發環境啟動-Dspring.profiles.active="dev"
生産環境啟動方式
- Linux 環境需要前往 Tomcat 的 /bin 目錄下,需要 ./catalina.sh 中的
内容如下JAVA_OPTS
-
JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=prod"