详解Spring中的Profile

2023-12-05

一. 前言

由于在项目中使用Maven打包部署的时候,经常由于配置参数过多(比如Nginx服务器的信息、ZooKeeper的信息、数据库连接、Redis服务器地址等),导致实际现网的配置参数与测试服务器参数混淆,一旦在部署的时候某个参数忘记修改了,那么就必须重新打包部署,这确实让人感到非常头疼。因此就想到使用Spring中的Profile来解决上面描述的问题,并且在此记录一下其使用的方式,如果有不对的地方,请指正!(感谢)。

本文从如下3方面探讨Spring的Profile:

  • Spring中的Profile是什么
  • 为什么要使用Profile
  • 如何使用Profile

二. Spring中的Profile 是什么?

Spring中的Profile功能其实早在Spring 3.1的版本就已经出来,它可以理解为我们在Spring容器中所定义的Bean的 逻辑组名称 ,只有当这些Profile被激活的时候,才会将Profile中所对应的Bean注册到Spring容器中。举个更具体的例子,我们以前所定义的Bean,当Spring容器一启动的时候,就会一股脑的全部加载这些信息完成对Bean的创建;而使用了Profile之后,它会将Bean的定义进行更细粒度的划分,将这些定义的Bean划分为几个不同的组,当Spring容器加载配置信息的时候,首先查找激活的Profile,然后只会去加载被激活的组中所定义的Bean信息,而不被激活的Profile中所定义的Bean定义信息是不会加载用于创建Bean的。

三. 配置Spring profile

在介绍完Profile以及为什么要使用它之后,下面让我们以一个例子来演示一下Profile的使用,这里还是使用传统的XML的方式来完成Bean的装配。

3.1 例子需要的Maven依赖

由于只是做一个简单演示,因此无需引入Spring其他模块中的内容,只需引入核心的4个模块+测试模块即可。

     <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--指定Spring版本,该版本必须大于等于3.1-->
        <spring.version>4.2.4.RELEASE</spring.version>
        <!--指定JDK编译环境-->
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

3.2 例子代码

本例使用 @ActiveProfiles 注解来激活profile;

package com.panlingxiao.spring.profile.service;

/**
 * 定义接口,在实际中可能是一个数据源
 * 在开发的时候与实际部署的时候分别使用不同的实现
 */
public interface HelloService {

    public String sayHello();
}

定义生产环境使用的实现类:

package com.panlingxiao.spring.profile.service.produce;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.panlingxiao.spring.profile.service.HelloService;

/**
 * 模拟在生产环境下需要使用的类
 */
@Component
public class ProduceHelloService implements HelloService {
    
    //这个值读取生产环境下的配置注入
    @Value("#{config.name}")
    private String name;

    public String sayHello() {
        return String.format("hello,I'm %s,this is a produce environment!",
                name);
    }
}

定义开发下使用的实现类:

package com.panlingxiao.spring.profile.service.dev;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.panlingxiao.spring.profile.service.HelloService;

/**
 * 模拟在开发环境下使用类
 */
@Component
public class DevHelloService implements HelloService{
    
    //这个值是读取开发环境下的配置文件注入
    @Value("#{config.name}")
    private String name;
    
    public String sayHello() {
        return String.format("hello,I'm %s,this is a development environment!", name);
    }

}

定义配置Spring配置文件:

<?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:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
    
    <!-- 定义开发的profile -->
    <beans profile="development">
        <!-- 只扫描开发环境下使用的类 -->
        <context:component-scan base-package="com.panlingxiao.spring.profile.service.dev" />
        <!-- 加载开发使用的配置文件 -->
        <util:properties id="config" location="classpath:dev/config.properties"/>
    </beans>

    <!-- 定义生产使用的profile -->
    <beans profile="produce">
        <!-- 只扫描生产环境下使用的类 -->
        <context:component-scan
            base-package="com.panlingxiao.spring.profile.service.produce" />
        <!-- 加载生产使用的配置文件 -->    
        <util:properties id="config" location="classpath:produce/config.properties"/>
    </beans>
</beans>

开发使用的配置文件,dev/config.properties:

    name=Tomcat

生产使用的配置文件,produce/config.properties:

	name=Jetty

编写测试类:

package com.panlingxiao.spring.profile.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.panlingxiao.spring.profile.service.HelloService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-profile.xml")
/*
 * 使用注册来完成对profile的激活,
 * 传入对应的profile名字即可,可以传入produce或者development
 */
@ActiveProfiles("produce")
public class TestActiveProfile {

    @Autowired
    private HelloService hs;
    
    @Test
    public void testProfile() throws Exception {
        String value = hs.sayHello();
        System.out.println(value);
    }
}

填写测试类中 @ActiveProfiles(" ") 注解中的profile名称(produce或者development)选择注入不同的bean!

输入 development
在这里插入图片描述

输入 dev
在这里插入图片描述

四. 激活Profile的其他几种方式

上面介绍了如何使用Profile以及在单元测试的环境下激活指定的Profile,除了使用 @ActiveProfiles 注解来激活profile外,Spring还提供了其他的几种激活Profile,这些方式在实际的开发中使用的更多。

Spring通过两个不同属性来决定哪些profile可以被激活(注意:profile是可以同时激活多个的),一个属性是 spring.profiles.active spring.profiles.default
这两个常量值在Spring的AbstractEnvironment中有定义,查看AbstractEnvironment源码:

    /**
     * Name of property to set to specify active profiles: {@value}. Value may be comma
     * delimited.
     * <p>Note that certain shell environments such as Bash disallow the use of the period
     * character in variable names. Assuming that Spring's {@link SystemEnvironmentPropertySource}
     * is in use, this property may be specified as an environment variable as
     * {@code SPRING_PROFILES_ACTIVE}.
     * @see ConfigurableEnvironment#setActiveProfiles
     */
    public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";

    /**
     * Name of property to set to specify profiles active by default: {@value}. Value may
     * be comma delimited.
     * <p>Note that certain shell environments such as Bash disallow the use of the period
     * character in variable names. Assuming that Spring's {@link SystemEnvironmentPropertySource}
     * is in use, this property may be specified as an environment variable as
     * {@code SPRING_PROFILES_DEFAULT}.
     * @see ConfigurableEnvironment#setDefaultProfiles
     */
    public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
    

如果当 spring.profiles.active 属性被设置时,那么Spring会优先使用该属性对应值来激活Profile。当spring.profiles.active没有被设置时,那么Spring会根据 spring.profiles.default 属性的对应值来进行Profile进行激活。
如果上面的两个属性都没有被设置,那么就不会有任务Profile被激活,只有定义在Profile之外的Bean才会被创建
我们发现这两个属性值其实是Spring容器中定义的属性,而我们在实际的开发中很少会直接操作Spring容器本身,所以如果要设置这两个属性,其实是需要定义在特殊的位置,让Spring容器自动去这些位置读取然后自动设置,这些位置主要为如下定义的地方:

  • 作为虚拟机的系统参数
  • 作为SpringMVC中的DispatcherServlet的初始化参数
  • 作为Web 应用上下文中的初始化参数
  • 作为JNDI的入口
  • 作为环境变量
  • 使用@AtivceProfiles 来进行激活

: 作为虚拟机的系统参数
在服务启动时在IDEA中设置VM参数:
在这里插入图片描述

我们在实际的使用过程中,可以定义默认的profile为开发环境,当实际部署的时候,主需要在实际部署的环境服务器中将spring.profiles.active定义在环境变量中来让Spring自动读取当前环境下的配置信息,这样就可以很好的避免不同环境而频繁修改配置文件的麻烦。

转自: https://www.jianshu.com/p/948c303b2253

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

详解Spring中的Profile 的相关文章

随机推荐

  • Elasticsearch-Kibana使用教程

    1 索引操作 1 1创建索引 PUT employee settings index refresh interval 1s number of shards 1 max result window 10000 number of repl
  • el-table 删除某行数据时 删除语句包含行号/序号

    el table可展示每行数据的序号列 在点击删除按钮的时候 会获取到该行所有的数据值 但是要想删除时提示到具体的序号 如 是否确认删除序号为1的数据项 我是这样写的 删除按钮操作 handleDelete row index用来存储该项数
  • Android中的Banner轮播图的使用

    目录 效果图 介绍 3 XML中banner常用的属性 使用 导入依赖 xml文件 活动代码 本文在碎片中使用 效果图 Banner效果图 介绍 Banner轮播图是一种常见的移动应用界面设计元素 用于展示多张图片或广告 并支持自动切换 它
  • “我,大三,寒假靠Python兼职赚了7567.6元。”

    目前很多同学已经结束期末考试 进入寒假 有很多同学问我 有什么兼职可以线上做的吗 最好还能提高自己的一些技能 以前周末或假期经常去当服务员 导购 发传单之类 最后发现 只是在无畏地消磨自己的时间 对本身技能并不能得到任何提高 所以 不想再重
  • 【王道】计算机组成原理笔记 第四章 指令系统

    前三章讲的分别是概述 运算器和存储器 接下来的第四章和第五章内容都是关于控制器的 我们知道 控制器通过指令来控制计算机 所以这一章介绍指令 下一章介绍控制器如何通过指令来控制计算机 4 1 1 指令格式 1 指令 操作码和地址码 1 1 指
  • linux内核机制之设备树

    设备树 Device Tree 基本概念及作用 在内核源码中 存在大量对板级细节信息描述的代码 这些代码充斥在 arch arm plat xxx和 arch arm mach xxx目录 对内核而言这些platform设备 resourc
  • 视频压缩怎么操作?看完这篇你就知道了

    亲们 你们是否经常为了视频文件过大而烦恼呢 别担心 现在有了视频压缩软件 我们可以轻松解决这个问题 视频压缩软件不仅在日常生活中大放异彩 也在工作和娱乐中发挥着重要的作用 无论是想要分享视频给朋友 还是上传到社交平台或视频网站 视频压缩软件
  • 企业如何为自己的未来做准备?

    如果企业不为未来做准备 就要为出局做准备工作 德鲁克 随着市场需求的不断变化 企业面对着激烈的市场竞争 其该如何为自己的未来做准备 具体企业面临着 建立竞争优势 管理多元化员工队伍 应用新的信息系统与技术 首先 企业在市场竞争中想要建立自己
  • 强化元学习算法在机器人控制中的应用研究

    随着人工智能和机器学习的快速发展 强化学习作为一种重要的机器学习方法 被广泛应用于机器人控制领域 然而 传统的强化学习算法在面对复杂任务和多样化环境时往往需要大量的训练时间和样本 为了解决这个问题 强化元学习算法应运而生 本文将探讨强化元学
  • 微信小程序自定义数据实现级联省市区组件

    前言 在微信小程序中 官方文档提供的省市区组件 可以让用户更加方便快捷地选择省市区 但是官方提供的组件有一个缺点 无法自定义数据 但如果项目中需要使用自己的数据 显然就得寻找其它的组件实现 官方组件 优点 使用官方组件具有稳定性和兼容性 可
  • 137-基于stm32单片机智能保温杯控制装置Proteus仿真+源程序

    资料编号 137 一 功能介绍 1 采用stm32单片机 LCD1602显示屏 独立按键 DS18B20传感器 电机 制作一个基于stm32单片机智能保温杯控制装置Proteus仿真 2 通过DS18b20传感器检测当前保温杯水的温度 并且
  • C++单例模式

    pragma once namespace utility 需要拼接一下命名空间 utility define SINGLETON x friend class utility Singleton
  • 136-基于stm32单片机家庭温湿度防漏水系统设计Proteus仿真+源程序

    资料编号 136 一 功能介绍 1 采用stm32单片机 LCD1602显示屏 独立按键 DHT11传感器 蜂鸣器 制作一个基于stm32单片机家庭温湿度防漏水系统设计Proteus仿真 2 通过DHT11传感器检测当前温湿度 并且显示到L
  • 编程分为哪几种

    前言 编程是一项广泛的技能 涉及到许多不同的编程语言和编程领域 以下是编程的一些常见类型 应用程序开发 开发桌面应用程序 移动应用程序 网络应用程序 游戏等等 例如 Java C C Python Swift Objective C Kot
  • 135-基于stm32单片机超声波非接触式感应水龙头控制系统Proteus仿真+源程序

    资料编号 135 一 功能介绍 1 采用stm32单片机 LCD1602显示屏 独立按键 DHT11传感器 电机 超声波传感器 制作一个基于stm32单片机超声波非接触式感应水龙头控制系统Proteus仿真 2 通过DHT11传感器检测当前
  • 使用python streamlit库快速创建一个购物网站

    streamlit Streamlit 是一个基于 Python 的 Web 应用程序框架 致力于以更高效 更灵活的方式可视化数据 并分析结果 Streamlit是一个开源库 可以帮助数据科学家和学者在短时间内开发机器学习 ML 可视化仪表
  • 强化学习在机器人导航中的路径规划策略分析

    机器人导航是指机器人在未知环境中自主移动的过程 路径规划是机器人导航中的一个重要问题 其目的是找到一条最优路径 使机器人能够快速 安全地到达目的地 传统的路径规划方法往往基于启发式算法 如A 算法 Dijkstra算法等 这些方法在一定程度
  • InterLM代码解析

    interLM的Transformer架构 重要模块的实现解析 Decoder架构 class InternLMDecoderLayer nn Module def init self config InternLMXComposerCon
  • 服务器托管与服务器租用的详细比较

    在当今数字化时代 服务器托管和服务器租用成为了许多企业和个人选择的两种常见方式 它们都提供了一种将服务器放置在专业机房中的解决方案 但在具体实施和使用过程中存在一些差异 下面将详细比较这两种方式的优势和劣势 1 服务器托管 服务器托管是指用
  • 详解Spring中的Profile

    详解Spring中的Profile 一 前言 二 Spring中的Profile 是什么 三 配置Spring profile 3 1 例子需要的Maven依赖 3 2 例子代码 四 激活Profile的其他几种方式 一 前言 由于在项目中