打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

配置多个数据源区分开发环境和正式环境变量,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就出来了= =

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
在spring配置jdbc
Spring Data Jpa 详解 (配置篇)
ssh 中使用c3p0 的连接池配置
使用Atomikos Transactions Essentials实现多数据源JTA分布式事务
Spring中配置数据源的4种形式
Spring + Atomikos 分布式事务实现方式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服