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

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

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

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

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

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

application.properties 作为生产环境;

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

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配置文件中配置对应的数据源:

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

<?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,也不会触及到生产环境。

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

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

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

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) {
	}

}

  

public class Config {

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

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

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

最后启动tomcat就出来了= =

原文地址:https://www.cnblogs.com/SimonHu1993/p/7451612.html