当前位置: 首页 > news >正文

Spring Profiles and @Profile

1. Overview

In this tutorial, we’ll focus on introducing Profiles in Spring.

Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for example, dev, test, and prod.

We can then activate different profiles in different environments to bootstrap only the beans we need.


2. Use @Profile on a Bean

Let’s start simple and look at how we can make a bean belong to a particular profile. We use the @Profile annotation — we are mapping the bean to that particular profile; the annotation simply takes the names of one (or multiple) profiles.


Consider a basic scenario: We have a bean that should only be active during development but not deployed in production.

We annotate that bean with a dev profile, and it will only be present in the container during development. In production, the dev simply won’t be active:

@Component
@Profile("dev")
public class DevDatasourceConfig

As a quick sidenote, profile names can also be prefixed with a NOT operator, e.g., !dev, to exclude them from a profile.

In the example, the component is activated only if dev profile is not active:

@Component
@Profile("!dev")
public class DevDatasourceConfig

3. Declare Profiles in XML

Profiles can also be configured in XML. The tag has a profile attribute, which takes comma-separated values of the applicable profiles:

<beans profile="dev"><bean id="devDatasourceConfig" class="org.baeldung.profiles.DevDatasourceConfig" />
</beans>

4. Set Profiles

The next step is to activate and set the profiles so that the respective beans are registered in the container.

This can be done in a variety of ways, which we’ll explore in the following sections.


4.1. Programmatically via WebApplicationInitializer Interface

In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically.

It’s also a very handy location to set our active profiles programmatically:

@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {servletContext.setInitParameter("spring.profiles.active", "dev");}
}

4.2. Programmatically via ConfigurableEnvironment

We can also set profiles directly on the environment:

@Autowired
private ConfigurableEnvironment env;
...
env.setActiveProfiles("dev");

4.3. Context Parameter in web.xml

Similarly, we can define the active profiles in the web.xml file of the web application, using a context parameter:

<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<context-param><param-name>spring.profiles.active</param-name><param-value>dev</param-value>
</context-param>

4.4. JVM System Parameter

The profile names can also be passed in via a JVM system parameter. These profiles will be activated during application startup:

-Dspring.profiles.active=dev

4.5. Environment Variable

In a Unix environment, profiles can also be activated via the environment variable:

export spring_profiles_active=dev

4.6. Maven Profile

Spring profiles can also be activated via Maven profiles, by specifying the spring.profiles.active configuration property.

In every Maven profile, we can set a spring.profiles.active property:

<profiles><profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation><properties><spring.profiles.active>dev</spring.profiles.active></properties></profile><profile><id>prod</id><properties><spring.profiles.active>prod</spring.profiles.active></properties></profile>
</profiles>

Its value will be used to replace the @spring.profiles.active@ placeholder in application.properties:

spring.profiles.active=@spring.profiles.active@

Now we need to enable resource filtering in pom.xml:

<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources>...
</build>

and append a -P parameter to switch which Maven profile will be applied:

mvn clean package -Pprod

This command will package the application for prod profile. It also applies the spring.profiles.active value prod for this application when it is running.


4.7. @ActiveProfile in Tests

Tests make it very easy to specify what profiles are active using the @ActiveProfile annotation to enable specific profiles:

@ActiveProfiles("dev")

So far, we’ve looked at multiple ways of activating profiles. Let’s now see which one has priority over the other and what happens if we use more than one, from highest to lowest priority:

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable
  5. Maven profile

5. The Default Profile

Any bean that does not specify a profile belongs to the default profile.

Spring also provides a way to set the default profile when no other profile is active — by using the spring.profiles.default property.


6. Get Active Profiles

Spring’s active profiles drive the behavior of the @Profile annotation for enabling/disabling beans. However, we may also wish to access the list of active profiles programmatically.

We have two ways to do it, using Environment or spring.profiles.active.


6.1. Using Environment

We can access the active profiles from the Environment object by injecting it:

public class ProfileManager {@Autowiredprivate Environment environment;public void getActiveProfiles() {for (String profileName : environment.getActiveProfiles()) {System.out.println("Currently active profile - " + profileName);}  }
}

6.2. Using spring.profiles.active

Alternatively, we could access the profiles by injecting the property spring.profiles.active:

@Value("${spring.profiles.active}")
private String activeProfile;

Here, our activeProfile variable will contain the name of the profile that is currently active,


-And if there are several, it’ll contain their names separated by a comma.

And if we want to access the list of them just like in the previous example, we can do it by splitting the activeProfile variable:

public class ProfileManager {@Value("${spring.profiles.active:}")private String activeProfiles;public String getActiveProfiles() {for (String profileName : activeProfiles.split(",")) {System.out.println("Currently active profile - " + profileName);}}
}

However, we should consider what would happen if there is no active profile at all. With our code above, the absence of an active profile would prevent the application context from being created. This would result in an IllegalArgumentException owing to the missing placeholder for injecting into the variable.


In order to avoid this, we can define a default value:

@Value("${spring.profiles.active:}")
private String activeProfile;

Now, if no profiles are active, our activeProfile will just contain an empty string.


7. Example: Separate Data Source Configurations Using Profiles

Now that the basics are out of the way, let’s take a look at a real example.

Consider a scenario where we have to maintain the data source configuration for both the development and production environments.

Let’s create a common interface DatasourceConfig that needs to be implemented by both data source implementations:

public interface DatasourceConfig {public void setup();
}

Following is the configuration for the development environment:

@Component
@Profile("dev")
public class DevDatasourceConfig implements DatasourceConfig {@Overridepublic void setup() {System.out.println("Setting up datasource for DEV environment. ");}
}

And configuration for the production environment:

@Component
@Profile("production")
public class ProductionDatasourceConfig implements DatasourceConfig {@Overridepublic void setup() {System.out.println("Setting up datasource for PRODUCTION environment. ");}
}

Now let’s create a test and inject our DatasourceConfig interface; depending on the active profile, Spring will inject DevDatasourceConfig or ProductionDatasourceConfig bean:

public class SpringProfilesWithMavenPropertiesIntegrationTest {@AutowiredDatasourceConfig datasourceConfig;public void setupDatasource() {datasourceConfig.setup();}
}

When the dev profile is active, Spring injects DevDatasourceConfig object, and when calling then setup() method, the following is the output:

Setting up datasource for DEV environment.

8. Profiles in Spring Boot

Spring Boot supports all the profile configuration outlined so far, with a few additional features.


8.1. Activating or Setting a Profile

The initialization parameter spring.profiles.active, introduced in Section 4, can also be set up as a property in Spring Boot to define currently active profiles. This is a standard property that Spring Boot will pick up automatically:

spring.profiles.active=dev

However, starting Spring Boot 2.4, this property cannot be used in conjunction with spring.config.activate.on-profile, as this could raise a ConfigDataException (i.e. an InvalidConfigDataPropertyException or an InactiveConfigDataAccessException).


To set profiles programmatically, we can also use the SpringApplication class:

SpringApplication.setAdditionalProfiles("dev");

To set profiles using Maven in Spring Boot, we can specify profile names under spring-boot-maven-plugin in pom.xml:

<plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><profiles><profile>dev</profile></profiles></configuration></plugin>...
</plugins>

and execute the Spring Boot-specific Maven goal:

mvn spring-boot:run

8.2. Profile-specific Properties Files

However, the most important profiles-related feature that Spring Boot brings is profile-specific properties files. These have to be named in the format application-{profile}.properties.

Spring Boot will automatically load the properties in an application.properties file for all profiles, and the ones in profile-specific.properties files only for the specified profile.


For example, we can configure different data sources for dev and production profiles by using two files named application-dev.properties and application-production.properties:

In the application-production.properties file, we can set up a MySql data source:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root

Then we can configure the same properties for the dev profile in the application-dev.properties file, to use an in-memory H2 database:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

In this way, we can easily provide different configurations for different environments.

Prior to Spring Boot 2.4, it was possible to activate a profile from profile-specific documents. But that is no longer the case; with later versions, the framework will throw – again – an InvalidConfigDataPropertyException or an InactiveConfigDataAccessException in these circumstances.


8.3. Multi-Document Files

To further simplify defining properties for separate environments, we can even club all the properties in the same file and use a separator to indicate the profile.

Starting version 2.4, Spring Boot has extended its support for multi-document files for properties files in addition to previously supported YAML. So now, we can specify the dev and production properties in the same application.properties:

my.prop=used-always-in-all-profiles
#---
spring.config.activate.on-profile=dev
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=root
spring.datasource.password=root
#---
spring.config.activate.on-profile=production
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

This file is read by Spring Boot in top to bottom order. That is, if some property, say my.prop, occurs once more at the end in the above example, the endmost value will be considered.


8.4. Profile Groups

Another feature added in Boot 2.4 is Profile Groups. As the name suggests, it allows us to group similar profiles together.

Let’s consider a use case where we'd have multiple configuration profiles for the production environment. Say, a proddb for the database and prodquartz for the scheduler in the production environment.

To enable these profiles all at once via our application.properties file, we can specify:

spring.profiles.group.production=proddb,prodquartz

Consequently, activating the production profile will activate proddb and prodquartz as well.


参考:
Spring Profiles

相关文章:

Spring Profiles and @Profile

1. Overview In this tutorial, we’ll focus on introducing Profiles in Spring. Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for example, dev, test, and prod. We can then activate different profiles…...

数据分析-数据探索

文章目录前言主要内容总结更多宝藏前言 &#x1f60e;&#x1f973;&#x1f60e;&#x1f920;&#x1f62e;&#x1f916;&#x1f648;&#x1f4ad;&#x1f373;&#x1f371; 随着大数据和人工智能技术的不断发展&#xff0c;数据分析已经成为了一种非常重要的技能和工…...

7个最受欢迎的Python库,大大提高开发效率

当第三方库可以帮我们完成需求时&#xff0c;就不要重复造轮子了 整理了GitHub上7个最受好评的Python库&#xff0c;将在你的开发之旅中提供帮助 PySnooper 很多时候时间都花在了Debug上&#xff0c;大多数人呢会在出错位置的附近使用print&#xff0c;打印某些变量的值 这个…...

Intellij IDEA 中调试 maven 插件

Intellij IDEA 中调试 maven 插件话痨一下步骤1. classfinal-demo 项目部分2. ClassFinal 部分参考资料话痨一下 目前有两个项目&#xff1a; ClassFinal 是一款java class文件安全加密工具。classfinal-demo 是我建的一个Demo&#xff0c;用来测试ClassFinal的加密效果。 目…...

Java全栈知识(1)缓存池

我们先看这么一道题 Integer x new Integer(123); Integer y new Integer(123); System.out.println(x y); // false Integer z 123; Integer k 123; System.out.println(z k); // true Integer a 200; Integer b 200; System.out.println(z k); //false 我们…...

网络安全的特性

0x00 前言 网络安全的特性包括&#xff0c;机密性&#xff0c;完整性&#xff0c;可用性&#xff0c;真实性和不可否认性。详细的内容可以参考如下的内容。 Xmind资源请下载~ 0x01 机密性 机密性&#xff08;Confidentiality&#xff09; 意味着阻止未经授权的实体&#x…...

YOLOv8 多目标跟踪

文章大纲 简介环境搭建代码样例跟踪原理代码分析原始老版实现新版本封装代码实现追踪与计数奇奇怪怪错误汇总lap 安装过程报错推理过程报错参考文献与学习路径简介 使用yolov8 做多目标跟踪 文档地址: https://docs.ultralytics.com/modes/track/https://github.com/ultralyt…...

Gitee搭建个人博客(Beautiful Jekyll)

目录一、引言二、博客模板选型 - Jekyll三、安装Jekyll环境3.1 安装Ruby3.2 安装Jekyll3.3 下载Jekyll主题四、搭建我的Gitee博客4.1 选择主题 - Beautiful Jekyll4.2 创建Gitee账号同名代码库4.3 写博客4.4 开通Gitee Pages服务五、对Beautifu Jekyll的相关优化一、引言 之前…...

图形视图框架 事件处理(item)

在图形界面框架中的事件都是先由视图进行接收&#xff0c;然后传递给场景&#xff0c;再由场景传递给图形项。通过键盘处理的话&#xff0c;需要设置焦点&#xff0c;在QGraphicsScene中使用setFoucesItem&#xff08;&#xff09;函数可以设置焦点&#xff0c;或者图形项使用s…...

PTA第六章作业详解

&#x1f680;write in front&#x1f680; &#x1f4dd;个人主页&#xff1a;认真写博客的夏目浅石. &#x1f381;欢迎各位→点赞&#x1f44d; 收藏⭐️ 留言&#x1f4dd; &#x1f4e3;系列专栏&#xff1a;夏目的作业 &#x1f4ac;总结&#xff1a;希望你看完之后&am…...

Java课程设计项目--音乐视频网站系统

一、功能介绍 随着社会的快速发展&#xff0c;计算机的影响是全面且深入的。人们生活水平的不断提高&#xff0c;日常生活中人们对音乐方面的要求也在不断提高&#xff0c;听歌的人数更是不断增加&#xff0c;使得音乐网站的设计的开发成为必需而且紧迫的事情。音乐网站的设计主…...

FPGA可以转IC设计吗?需要学习哪些技能?

曾经在知乎上看到一个回答“入职做FPGA&#xff0c;后续是否还可以转数字IC设计&#xff1f;” 从下面图内薪资就可以对比出来&#xff0c;对比FPGA的行业薪资水平&#xff0c;IC行业中的一些基础性岗位薪资比很多FPGA大多数岗位薪资都要高。 除了薪资之外更多FPGA转IC设计的有…...

初探Gradle

目录一.概述二.优点三.安装与配置1. 官网下载2. 配置环境变量3. 检验4. 配置国内镜像(可选)5. IDEA配置三.工程结构四.生命周期1.Initialization阶段2.Configuration阶段3.Execution阶段五.Task六.常用任务指令七.引入依赖1.本地依赖2.项目依赖3.直接依赖八.依赖类型九.插件十.…...

国产数据库介绍

人大金仓 Kingbase 北京人大金仓信息技术股份有限公司于1999年由中共人民大学专家创立&#xff0c;自成立以来&#xff0c;始终立足自主研发&#xff0c;专注数据管理领域&#xff0c;先后承担了国家“863”、“核高基”等重大专项&#xff0c;研发出了具有国际先进水平的大型…...

Java OpenJudge-test3

目录 1:明明的随机数 2:合影效果 3:不重复的单词 4:和为给定数 5:字符串数组排序问题 6:字符串排序 7:求序列中的众数 1:明明的随机数 总时间限制: 1000ms 内存限制: 65536kB 描述 明明想在学校中请一些同学一起做一项问卷调查&#xff0c;为了实验的客观性&#xff…...

蓝桥杯刷题冲刺 | 倒计时22天

作者&#xff1a;指针不指南吗 专栏&#xff1a;蓝桥杯倒计时冲刺 &#x1f43e;马上就要蓝桥杯了&#xff0c;最后的这几天尤为重要&#xff0c;不可懈怠哦&#x1f43e; 文章目录1.选数异或2.特殊年份1.选数异或 题目 链接&#xff1a; 选数异或 - 蓝桥云课 (lanqiao.cn) 给定…...

入行 5年,跳槽 3次,我终于摸透了软件测试这行(来自过来人的忠告)

目录 前言 第一年 第二年 第三年 第四年 作为过来人的一些忠告 前言 最近几年行业在如火如荼的发展壮大&#xff0c;以及其他传统公司都需要大批量的软件测试人员&#xff0c;但是20年的疫情导致大规模裁员&#xff0c;让人觉得行业寒冬已来&#xff0c;软件测试人员的职…...

开源时序数据库学习

计划学习使用QuestDB解决大数据日志存储场景。以下是常见引擎比较 比较项目 InfluxDB TimescaleDB OpenTSDB QuestDB 数据模型 Key-Value Relational Key-Value Relational 存储引擎 自主开发的TSI PostgreSQL扩展程序 Apache HBase 自主开发 查询语言 InfluxQ…...

字节测试工程师悄悄告诉我的软件测试、测试开发常用的测试策略与测试手段

目录 前言 测试策略的关注重点 测试策略主要内容 总体测试策略 初级版本测试策略 跟踪测试执行 版本质量评估 后续版本测试策略 发布质量评估 测试手段 前言 测试策略是指在特定环境约束之下&#xff0c;描述软件开发周期中关于测试原则、方法、方式的纲要&#xff…...

我常用的shell 进制转换工具

一、进制的一些基础知识 1. 二进制&#xff08;binary&#xff09; 二进制的取值是0和1; 前缀是 0b 2. 八进制&#xff08;Octal&#xff09; 八进制的取值是0-7&#xff1b;前缀是 O 3. 十进制&#xff08;decimal&#xff09; 十进制的取值是0-9&#xff1b;没有前缀 …...

Java 语言特性(面试系列1)

一、面向对象编程 1. 封装&#xff08;Encapsulation&#xff09; 定义&#xff1a;将数据&#xff08;属性&#xff09;和操作数据的方法绑定在一起&#xff0c;通过访问控制符&#xff08;private、protected、public&#xff09;隐藏内部实现细节。示例&#xff1a; public …...

Swift 协议扩展精进之路:解决 CoreData 托管实体子类的类型不匹配问题(下)

概述 在 Swift 开发语言中&#xff0c;各位秃头小码农们可以充分利用语法本身所带来的便利去劈荆斩棘。我们还可以恣意利用泛型、协议关联类型和协议扩展来进一步简化和优化我们复杂的代码需求。 不过&#xff0c;在涉及到多个子类派生于基类进行多态模拟的场景下&#xff0c;…...

【解密LSTM、GRU如何解决传统RNN梯度消失问题】

解密LSTM与GRU&#xff1a;如何让RNN变得更聪明&#xff1f; 在深度学习的世界里&#xff0c;循环神经网络&#xff08;RNN&#xff09;以其卓越的序列数据处理能力广泛应用于自然语言处理、时间序列预测等领域。然而&#xff0c;传统RNN存在的一个严重问题——梯度消失&#…...

江苏艾立泰跨国资源接力:废料变黄金的绿色供应链革命

在华东塑料包装行业面临限塑令深度调整的背景下&#xff0c;江苏艾立泰以一场跨国资源接力的创新实践&#xff0c;重新定义了绿色供应链的边界。 跨国回收网络&#xff1a;废料变黄金的全球棋局 艾立泰在欧洲、东南亚建立再生塑料回收点&#xff0c;将海外废弃包装箱通过标准…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

Maven 概述、安装、配置、仓库、私服详解

目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...

【VLNs篇】07:NavRL—在动态环境中学习安全飞行

项目内容论文标题NavRL: 在动态环境中学习安全飞行 (NavRL: Learning Safe Flight in Dynamic Environments)核心问题解决无人机在包含静态和动态障碍物的复杂环境中进行安全、高效自主导航的挑战&#xff0c;克服传统方法和现有强化学习方法的局限性。核心算法基于近端策略优化…...

人工智能(大型语言模型 LLMs)对不同学科的影响以及由此产生的新学习方式

今天是关于AI如何在教学中增强学生的学习体验&#xff0c;我把重要信息标红了。人文学科的价值被低估了 ⬇️ 转型与必要性 人工智能正在深刻地改变教育&#xff0c;这并非炒作&#xff0c;而是已经发生的巨大变革。教育机构和教育者不能忽视它&#xff0c;试图简单地禁止学生使…...

处理vxe-table 表尾数据是单独一个接口,表格tableData数据更新后,需要点击两下,表尾才是正确的

修改bug思路&#xff1a; 分别把 tabledata 和 表尾相关数据 console.log() 发现 更新数据先后顺序不对 settimeout延迟查询表格接口 ——测试可行 升级↑&#xff1a;async await 等接口返回后再开始下一个接口查询 ________________________________________________________…...

计算机基础知识解析:从应用到架构的全面拆解

目录 前言 1、 计算机的应用领域&#xff1a;无处不在的数字助手 2、 计算机的进化史&#xff1a;从算盘到量子计算 3、计算机的分类&#xff1a;不止 “台式机和笔记本” 4、计算机的组件&#xff1a;硬件与软件的协同 4.1 硬件&#xff1a;五大核心部件 4.2 软件&#…...