Spring Boot - Profile配置

简介: Profile是什么Profile我也找不出合适的中文来定义,简单来说,Profile就是Spring Boot可以对不同环境或者指令来读取不同的配置文件。

Profile是什么

Profile我也找不出合适的中文来定义,简单来说,Profile就是Spring Boot可以对不同环境或者指令来读取不同的配置文件。

Profile使用

假如有开发、测试、生产三个不同的环境,需要定义三个不同环境下的配置。

基于properties文件类型

你可以另外建立3个环境下的配置文件:

applcation.properties
application-dev.properties
application-test.properties
application-prod.properties

然后在applcation.properties文件中指定当前的环境:
spring.profiles.active=test
这时候读取的就是application-test.properties文件。

基于yml文件类型

只需要一个applcation.yml文件就能搞定,推荐此方式。

spring:
  profiles: 
    active: prod

---
spring: 
  profiles: dev  
  
server: 
  port: 8080  
  
---
spring: 
  profiles: test  
  
server: 
  port: 8081    
  
---
spring.profiles: prod
spring.profiles.include:
  - proddb
  - prodmq
  
server: 
  port: 8082      
  
---
spring: 
  profiles: proddb  
  
db:
  name: mysql   
  
---
spring: 
  profiles: prodmq   

mq: 
  address: localhost

此时读取的就是prod的配置,prod包含proddb,prodmq,此时可以读取proddb,prodmq下的配置。

也可以同时激活三个配置。

spring.profiles.active: prod,proddb,prodmq

基于Java代码

在JAVA配置代码中也可以加不同Profile下定义不同的配置文件,@Profile注解只能组合使用@Configuration和@Component注解。

@Configuration
@Profile("prod")
public class ProductionConfiguration {

    // ...

}

指定Profile

main方法启动方式:

// 在Eclipse Arguments里面添加
--spring.profiles.active=prod

插件启动方式:

spring-boot:run -Drun.profiles=prod

jar运行方式:

java -jar xx.jar --spring.profiles.active=prod

除了在配置文件和命令行中指定Profile,还可以在启动类中写死指定,通过SpringApplication.setAdditionalProfiles方法。

SpringApplication.class

public void setAdditionalProfiles(String... profiles) {
    this.additionalProfiles = new LinkedHashSet<String>(Arrays.asList(profiles));
}

推荐:Spring Boot & Cloud 最强技术教程

扫描关注我们的微信公众号,干货每天更新。

image
相关文章
|
16天前
|
存储 Java 数据安全/隐私保护
|
1天前
|
消息中间件 开发框架 Java
什么是Spring Boot 自动配置?
Spring Boot 是一个流行的 Java 开发框架,它提供了许多便利的功能和工具,帮助开发者快速构建应用程序。其中一个最引人注目的特性是其强大的自动配置功能。
6 0
|
2天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
10 1
|
3天前
|
Java Spring
Spring文件配置以及获取
Spring文件配置以及获取
11 0
|
10天前
|
Java 微服务 Spring
Spring Boot中获取配置参数的几种方法
Spring Boot中获取配置参数的几种方法
21 2
|
12天前
|
消息中间件 安全 Java
在Spring Bean中,如何通过Java配置类定义Bean?
【4月更文挑战第30天】在Spring Bean中,如何通过Java配置类定义Bean?
20 1
|
13天前
|
Java 开发者 Spring
Spring Boot中的资源文件属性配置
【4月更文挑战第28天】在Spring Boot应用程序中,配置文件是管理应用程序行为的重要组成部分。资源文件属性配置允许开发者在不重新编译代码的情况下,对应用程序进行灵活地配置和调整。本篇博客将介绍Spring Boot中资源文件属性配置的基本概念,并通过实际示例展示如何利用这一功能。
23 1
|
17天前
|
Java Spring 容器
如何用基于 Java 配置的方式配置 Spring?
如何用基于 Java 配置的方式配置 Spring?
|
17天前
|
存储 前端开发 Java
第十一章 Spring Cloud Alibaba nacos配置中心
第十一章 Spring Cloud Alibaba nacos配置中心
22 0
|
22天前
|
存储 安全 Java
第2章 Spring Security 的环境设置与基础配置(2024 最新版)(下)
第2章 Spring Security 的环境设置与基础配置(2024 最新版)(下)
23 0