软件开发过程一般涉及“开发 -> 测试 -> 部署上线”多个阶段,每个阶段的环境的配置参数会有不同,如数据源,文件路径等。为避免每次切换环境时都要进行参数配置等繁琐的操作,可以通过spring的profile功能来进行配置参数的切换。

以我用到的项目的实际情况为例,首先可以在resources文件夹下分别为每个环境建立单独的文件夹(也可以额外建立一个common文件夹,用于存放公共的参数配置文件),每个文件夹下面存放对应的环境所需的配置文件,就像这样子:

在resources文件夹下建立applicationContext-profile.xml文件,用来定义不同的profile:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd"> <description>spring profile配置</description> <!-- 开发环境配置文件 -->
<beans profile="development">
<context:property-placeholder
location="classpath*:common/*.properties, classpath*:development/*.properties" />
</beans> <!-- 测试环境配置文件 -->
<beans profile="test">
<context:property-placeholder
location="classpath*:common/*.properties, classpath*:test/*.properties" />
</beans> <!-- 生产环境配置文件 -->
<beans profile="production">
<context:property-placeholder
location="classpath*:common/*.properties, classpath*:production/*.properties" />
</beans> </beans>

这样就实现了通过profile标记不同的环境,接下来就可以通过设置spring.profiles.default和spring.profiles.active这两个属性来激活和使用对应的配置文件。default为默认,如果没有通过active来指定,那么就默认使用default定义的环境。

这两个属性可以通过多种方法来设置:

  • 在web.xml中作为web应用的上下文参数context-param;
  • 在web.xml中作为DispatcherServlet的初始化参数;
  • 作为JNDI条目;
  • 作为环境变量;
  • 作为JVM的系统属性;
  • 在集成测试类上,使用@ActiveProfiles注解配置。

前两者都可以在web.xml文件中设置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Archetype Created Web Application</display-name> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext*.xml
</param-value>
</context-param> <!-- 在上下文context-param中设置profile.default的默认值 -->
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>development</param-value>
</context-param> <!-- 在上下文context-param中设置profile.active的默认值 -->
<!-- 设置active后default失效,web启动时会加载对应的环境信息 -->
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>development</param-value>
</context-param> <servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 在DispatcherServlet参数中设置profile的默认值,active同理 -->
<init-param>
<param-name>spring.profiles.default</param-name>
<param-value>development</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> </web-app>

激活指定的环境,也可以通过JVM参数来设置,可以在tomcat的启动脚本中加入以下JVM参数来激活:

-Dspring.profiles.active="production"

在程序中,也可以通过 @Profile("...") 对某些资源进行注解,这样只有当选择对应的环境时,才会产生对应的bean,如:

/**
* 容器配置类
* 用于测试@Profile注解
*/
@Configuration
@PropertySource(value = {"classpath:/dbconfig.properties"})
public class ProfileBeanConfig implements EmbeddedValueResolverAware { //数据库连接用户名
@Value(value = "${jdbc.username}")
private String username;
//数据库连接密码
private String password; //开发环境数据源
@Bean(value = "dataSourceDev")
@Profile(value = "dev")
public DataSource dataSourceDev(@Value("${jdbc.driverClass}") String driverClass) throws PropertyVetoException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser(this.username);
comboPooledDataSource.setPassword(this.password);
comboPooledDataSource.setDriverClass(driverClass);
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
return comboPooledDataSource;
} //测试环境数据源
@Bean(value = "dataSourceTest")
@Profile("test")
public DataSource dataSourceTest(@Value("${jdbc.driverClass}") String driverClass) throws PropertyVetoException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser(this.username);
comboPooledDataSource.setPassword(this.password);
comboPooledDataSource.setDriverClass(driverClass);
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
return comboPooledDataSource;
} //生产环境数据源
@Bean(value = "dataSourceProduction")
@Profile("production")
public DataSource dataSourceProduction(@Value("${jdbc.driverClass}") String driverClass) throws PropertyVetoException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser(this.username);
comboPooledDataSource.setPassword(this.password);
comboPooledDataSource.setDriverClass(driverClass);
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/production");
return comboPooledDataSource;
} //获取字符串解析器
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
//解析配置文件,然后对数据库连接密码进行赋值
this.password = resolver.resolveStringValue("jdbc.password");
}
}

以下是切换数据源示例

//创建匿名容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
//设置环境,其值为@Profile注解的属性值
applicationContext.getEnvironment().setActiveProfiles("test");
//注册容器类
applicationContext.register(ProfileBeanConfig.class);
//刷新容器
applicationContext.refresh();

 

Spring详解(十)------spring 环境切换的更多相关文章

  1. 超全详解Java开发环境搭建

    摘自:https://www.cnblogs.com/wangjiming/p/11278577.html 超全详解Java开发环境搭建   在项目产品开发中,开发环境搭建是软件开发的首要阶段,也是必 ...

  2. NPOI2.2.0.0实例详解(十)—设置EXCEL单元格【文本格式】 NPOI 单元格 格式设为文本 HSSFDataFormat

    NPOI2.2.0.0实例详解(十)—设置EXCEL单元格[文本格式] 2015年12月10日 09:55:17 阅读数:3150 using System; using System.Collect ...

  3. Spring详解(一)------概述

    本系列教程我们将对 Spring 进行详解的介绍,相信你在看完后一定能够有所收获. 1.什么是 Spring ? Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开 ...

  4. Spring详解

    https://gitee.com/xiaomosheng888老师的码云 1.核心容器:核心容器提供 Spring 框架的基本功能(Spring Core).核心容器的主要组件是 BeanFacto ...

  5. Spring详解------概述

    1.什么是 Spring ? Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2E ...

  6. RabbitMQ Exchange详解以及Spring中Topic实战

    前言 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计.消息中间件主要用于组件之间的解耦. 业务需求 ...

  7. Spring系列20:注解详解和Spring注解增强(基础内功)

    有部分小伙伴反馈说前面基于注解的Spring中大量使用注解,由于对Java的注解不熟悉,有点难受.建议总结一篇的Java注解的基础知识,那么,它来了! 本文内容 什么是注解? 如何定义注解 如何使用注 ...

  8. Spring事务隔离级别与传播机制详解,spring+mybatis+atomikos实现分布式事务管理

    原创说明:本文为本人原创作品,绝非他处转载,转账请注明出处 1.事务的定义:事务是指多个操作单元组成的合集,多个单元操作是整体不可分割的,要么都操作不成功,要么都成功.其必须遵循四个原则(ACID). ...

  9. Spring Boot Admin 详解(Spring Boot 2.0,基于 Eureka 的实现)

    原文:https://blog.csdn.net/hubo_88/article/details/80671192 Spring Boot Admin 用于监控基于 Spring Boot 的应用,它 ...

随机推荐

  1. C语言经典试题--指针

    分享一道C语言的经典的题目.题目要求如下: 利用字符指针实现字符串1"I Love China"与字符串2"So do I"的输出.然后利用字符指针将字符串2的 ...

  2. springMVC-6-restful_CRUD

    1.大体框架 POJO层代码 Employee @Data public class Employee { private Integer id; private String lastName; p ...

  3. PAT乙级:1070 结绳 (25分)

    PAT乙级:1070 结绳 (25分) 题干 给定一段一段的绳子,你需要把它们串成一条绳.每次串连的时候,是把两段绳子对折,再如下图所示套接在一起.这样得到的绳子又被当成是另一段绳子,可以再次对折去跟 ...

  4. Java实战:教你如何进行数据库分库分表

    摘要:本文通过实际案例,说明如何按日期来对订单数据进行水平分库和分表,实现数据的分布式查询和操作. 本文分享自华为云社区<数据库分库分表Java实战经验总结 丨[绽放吧!数据库]>,作者: ...

  5. SSM框架中,利用ajax,jQuery,json动态刷新局部页面,实现用户名查重提示

    1.在applicationContext.xml配置json文件 2.jsp页面 3.js语句 js语句在script标签中使用, 4.控制层 5.逻辑处理层 6.Dao层方法 7.Mapping层 ...

  6. PGSQL基础语句汇总

    一.pgsql里面的数据类型不再介绍:https://www.runoob.com/postgresql/postgresql-data-type.html 二.常用基本语句 2.1.CREATE D ...

  7. SLF4J日志桥接的应用

    最近在给公司的测试部门开发一套自动化测试框架,为了是框架产生的测试报告更易于分析,我考虑将每一个用例与运行过程中产生的日志相关联,为了实现这样的效果,首先就需要统一项目的日志输出,那么具体怎么做呢? ...

  8. cytoscape-d3-force api

    { animate:true,//是否在布局运行时显示布局:特殊的"结束"值使布局具有离散布局的动画效果 maxIterations:0,//布局退出前的最大迭代次数 maxSim ...

  9. phpmyadmin scripts/setup.php 反序列化漏洞(WooYun-2016-199433)

    phpmyadmin 2.x版本 POST /scripts/setup.php HTTP/1.1 Host: 192.168.49.2:8080 Accept-Encoding: gzip, def ...

  10. linux中的dhcp

    目录 一.DHCP服务 二.DHCP的租约过程 三.使用DHCP动态配置主机地址 四.安装DHCP服务器 一.DHCP服务 ① DHCP (Dynamic HostConfiguration Prot ...