配置多个数据源,spring profile 多环境配置管理

针对生产环境,测试环境,以及本地调试开发有时会配置多套数据库,在一个数据配置文件进行修改,往往有时发布到生成环境会忘记修改,或者本地调试时还是生产环境的库,会导致生产环境数据被污染。

ps--刚开始配完发现在Myeclipse一直是“development”模式,后来发现tomcat配置完之后要myeclise中进行jdk配置。

1.这里我们可以配置多个数据源配置文件:

application.development.properties 作为开发环境;

application.local.properties 作为本地调试环境;

application.properties 作为生产环境;

application.test.properties 作为测试环境;

1

2

3

4

5

6

7

8

9

10

11

12

jdbc.driver=com.mysql.jdbc.Driver

#development

jdbc.url=jdbc:mysql://ip:port/database?autoReconnect=true&initialTimeout=3&useUnicode=true&characterEncoding=utf-8

jdbc.username=user

jdbc.password=password

#connection pool settings

jdbc.pool.minIdle=1

jdbc.pool.maxIdle=3

jdbc.pool.maxActive=30

jdbc.pool.maxWait=12000

  

2.然后在applicationContext.xml配置文件中配置对应的数据源:

配置文件有点长,主要是我配置了四个数据源,耐心点看吧- -

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  

    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:jpa="http://www.springframework.org/schema/data/jpa"

    xsi:schemaLocation="

        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd

        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"

    default-lazy-init="true">

    <description>Spring公共配置 </description>

    <context:annotation-config />

     

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->

    <context:component-scan base-package="com.eteclab.wodm">

        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>

    </context:component-scan>

    <!-- Jpa Entity Manager 配置 -->

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 

        <property name="dataSource" ref="dataSource"/>

        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>

        <property name="packagesToScan" value="com.eteclab"/>

        <property name="jpaProperties">

            <props>

                <!-- 命名规则 My_NAME->MyName -->

                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>

            </props>

        </property>

    </bean>

     

    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">

        <property name="databasePlatform">

            <bean factory-method="getDialect" class="org.eteclab.modules.persistence.Hibernates">

                <constructor-arg ref="dataSource"/>

            </bean>

        </property>

    </bean>

    <!-- Spring Data Jpa配置 -->

    <jpa:repositories base-package="com.eteclab.wodm"  transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>

    

    <!-- Jpa 事务配置 -->

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

        <property name="entityManagerFactory" ref="entityManagerFactory"/>

    </bean>

    <!-- 使用annotation定义事务 -->

    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

    <!-- JSR303 Validator定义 -->

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

     

    <!-- production环境 -->

    <beans profile="production">

        <context:property-placeholder ignore-unresolvable="true" 

        location="classpath*:/application.properties"/>  

         

        <!-- 数据源配置, 使用Tomcat JDBC连接池 -->

        <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">

            <!-- Connection Info -->

            <property name="driverClassName" value="${jdbc.driver}" />

            <property name="url" value="${jdbc.url}" />

            <property name="username" value="${jdbc.username}" />

            <property name="password" value="${jdbc.password}" />

         

            <!-- 连接数控制与连接归还策略 -->

            <property name="maxActive" value="${jdbc.pool.maxActive}" />

            <property name="maxIdle" value="${jdbc.pool.maxIdle}" />

            <property name="minIdle" value="${jdbc.pool.minIdle}" />

            <property name="maxWait" value="${jdbc.pool.maxWait}" />

            <property name="defaultAutoCommit" value="false" />

            <!-- 连接Idle一个小时后超时 -->

            <property name="timeBetweenEvictionRunsMillis" value="30000" />

            <property name="minEvictableIdleTimeMillis" value="30000" />

            <!-- 应对网络不稳定的策略 -->

            <!-- <property name="testOnBorrow" value="true" />

            <property name="validationInterval" value="30000" />

            <property name="validationQuery" value="select 1 from dual" /> -->

             <property name="testOnReturn" value="true"></property>

             <property name="testWhileIdle" value="true"></property>

            <property name="testOnBorrow" value="true" />

            <property name="validationInterval" value="30000" />

            <property name="validationQuery" value="select 1 from dual" />

            <!-- 应对连接泄漏的策略 -->

            <property name="removeAbandoned" value="true" />

            <property name="removeAbandonedTimeout" value="60" />

        </bean>

         

        <!-- 数据源配置,使用应用服务器的数据库连接池 -->

        <!--<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/ExampleDB" />-->

    </beans>

     

    <!-- local development环境 -->

    <beans profile="development">

        <context:property-placeholder ignore-resource-not-found="true"

            location="classpath*:/application.development.properties" /> 

        <!-- Tomcat JDBC连接池 -->

        <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">

            <!-- Connection Info -->

            <property name="driverClassName" value="${jdbc.driver}" />

            <property name="url" value="${jdbc.url}" />

            <property name="username" value="${jdbc.username}" />

            <property name="password" value="${jdbc.password}" />

         

            <!-- 连接数控制与连接归还策略 -->

            <property name="maxActive" value="${jdbc.pool.maxActive}" />

            <property name="maxIdle" value="${jdbc.pool.maxIdle}" />

            <property name="minIdle" value="${jdbc.pool.minIdle}" />

            <property name="maxWait" value="${jdbc.pool.maxWait}" />

            <property name="defaultAutoCommit" value="false" />

            <!-- 连接Idle一个小时后超时 -->

            <property name="timeBetweenEvictionRunsMillis" value="30000" />

            <property name="minEvictableIdleTimeMillis" value="30000" />

            <!-- 应对网络不稳定的策略 -->

            <property name="testOnBorrow" value="true" />

            <property name="validationInterval" value="30000" />

            <property name="validationQuery" value="select 1 from dual" />

            <!-- 应对连接泄漏的策略 -->

            <property name="removeAbandoned" value="true" />

            <property name="removeAbandonedTimeout" value="60" />

        </bean>

    </beans>

     

    <!-- local test 环境 -->

    <beans profile="local">

        <context:property-placeholder ignore-resource-not-found="true"

            location="classpath*:/application.local.properties" />   

        <!-- Tomcat JDBC连接池 -->

        <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">

            <!-- Connection Info -->

            <property name="driverClassName" value="${jdbc.driver}" />

            <property name="url" value="${jdbc.url}" />

            <property name="username" value="${jdbc.username}" />

            <property name="password" value="${jdbc.password}" />

         

            <!-- 连接数控制与连接归还策略 -->

            <property name="maxActive" value="${jdbc.pool.maxActive}" />

            <property name="maxIdle" value="${jdbc.pool.maxIdle}" />

            <property name="minIdle" value="${jdbc.pool.minIdle}" />

            <property name="maxWait" value="${jdbc.pool.maxWait}" />

            <property name="defaultAutoCommit" value="false" />

            <!-- 连接Idle一个小时后超时 -->

            <property name="timeBetweenEvictionRunsMillis" value="30000" />

            <property name="minEvictableIdleTimeMillis" value="30000" />

            <!-- 应对网络不稳定的策略 -->

            <property name="testOnBorrow" value="true" />

            <property name="validationInterval" value="30000" />

            <property name="validationQuery" value="select 1 from dual" />

            <!-- 应对连接泄漏的策略 -->

            <property name="removeAbandoned" value="true" />

            <property name="removeAbandonedTimeout" value="60" />

        </bean>

    </beans>

     

    <!-- unit test环境 -->

    <beans profile="test">

        <context:property-placeholder ignore-resource-not-found="true"

            location="classpath*:/application.test.properties" />    

         

        <!-- Tomcat JDBC连接池 -->

        <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">

            <!-- Connection Info -->

            <property name="driverClassName" value="${jdbc.driver}" />

            <property name="url" value="${jdbc.url}" />

            <property name="username" value="${jdbc.username}" />

            <property name="password" value="${jdbc.password}" />

         

            <!-- 连接数控制与连接归还策略 -->

            <property name="maxActive" value="${jdbc.pool.maxActive}" />

            <property name="maxIdle" value="${jdbc.pool.maxIdle}" />

            <property name="minIdle" value="${jdbc.pool.minIdle}" />

            <property name="maxWait" value="${jdbc.pool.maxWait}" />

            <property name="defaultAutoCommit" value="false" />

            <!-- 连接Idle一个小时后超时 -->

            <property name="timeBetweenEvictionRunsMillis" value="30000" />

            <property name="minEvictableIdleTimeMillis" value="30000" />

            <!-- 应对网络不稳定的策略 -->

            <property name="testOnBorrow" value="true" />

            <property name="validationInterval" value="30000" />

            <property name="validationQuery" value="select 1 from dual" />

            <!-- 应对连接泄漏的策略 -->

            <property name="removeAbandoned" value="true" />

            <property name="removeAbandonedTimeout" value="60" />

        </bean>

    </beans>

</beans>

 3.对tomcat服务器进行修改:

{tomcat_home}

/bin/catalina.bat 或 catalina.sh 以确定tomcat所在服务器的环境

{production, development, local, test}


对于windows操作系统,在catalina.bat的第二行,增加如下的语句


set CATALINA_OPTS=%CATALINA_OPTS% -Dspring.profiles.active="production"

对于linux操作系统,在catalina.sh的第二行,增加如下的语句

CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=\"production\""

注意这里的"production",只能是{production, development, local, test}
中的一个

例如我在我本地开发,使用“local”配置:

 还有一步要注意的地方就是在web.xml文件中:

配置默认为开发环境,这样如果新接触项目的开发人员如果本地没有配置tomcat,也不会触及到生产环境。

*************************************************************************************************

*************************************************************************************************

这里我们可以在项目中写一个监听类,来监听项目运行时所属的环境:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

public class InitConfigListener  implements ServletContextListener {

     

    public void contextInitialized(ServletContextEvent sce) {

        //侦测jvm环境,并缓存到全局变量中

        String env = System.getProperty("spring.profiles.active");

        if(env == null) {

            Config.ENV = "development";

        else {

            Config.ENV = env;

        }

         

        System.out.println("==================================================================================================");

        System.out.println("The Application "+sce.getServletContext().getServletContextName()+" is running on the environment:" + Config.ENV);

        System.out.println("==================================================================================================");

    }

    @Override

    public void contextDestroyed(ServletContextEvent arg0) {

    }

}

  

1

2

3

4

5

public class Config {

    public static String ENV = "development";//默认开发常量

     

}

  直接启动tomcat看到如下效果:

当然我们更希望是在Myeclise开发工具中启动- -

最后启动tomcat就出来了= =

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值