SpringBoot Profiles官网学习记录

"本文详细介绍了SpringBoot如何通过@Profile注解管理和激活不同的配置文件,包括在application.properties或yaml中设置spring.profiles.active,以及编程方式设置激活配置。同时讲解了配置文件的命名规则,如application-{profile}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网地址

springboot 2.6.6
官网链接
spring profiles提供了一个分离应用程序部分的方法,使其在特定的环境中可用
通过标记@Profile来限制什么时候加载@Component, @Configuration 或者 @ConfigurationProperties
例如如下实例:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {
}

笔记

如果@ConfigurationProperties bean是通过@ enableconfigationproperties而不是自动扫描注册的,
则需要在具有@ enableconfigationproperties注释的@Configuration类上指定@Profile注释。
在扫描@ConfigurationProperties的情况下,
@Profile可以在@ConfigurationProperties类本身上指定。

你可以在application.properties中通过spring.profiles.active来指定哪些配置是被启用的
application.properties中配置如下:

spring.profiles.active=dev,hsqldb

在yaml中配置如下

spring:
  profiles:
    active: "dev,hsqldb"

你也可以在命令行使用如下命令:--spring.profiles.active=dev,hsqldb达到上述同样效果

如果没有配置文件处于激活状态,则启用默认配置文件。默认配置文件的名称为default,可以使用spring.profiles.default 环境属性进行切换,如下所示:

application.properties中配置如下:

spring.profiles.default=none
spring:
  profiles:
    default: "none"

spring.profiles.active 和 spring.profiles.default只能在非配置文件特定的文档中使用。
这意味着它们不能包含在配置文件特定的文件
或spring.config.activate.on-profile激活的文档中

# 这个文档是有效的
spring.profiles.active=prod
#---
# 这个文档是无效的
spring.config.activate.on-profile=prod
spring.profiles.active=metrics
# 这个文档是无效的
spring:
  profiles:
    active: "prod"
---
# 这个文档是有效的
spring:
  config:
    activate:
      on-profile: "prod"
  profiles:
    active: "metrics"

添加激活配置文件

以application-{profile}格式的.properties和.yml文件
application.properties或application.yml中通过spring.profiles.active设置激活的属性文件
spring.profiles.active={profile}
实际开发中application-dev.properties,application-prod.properties,application-test.properties
分别表示开发环境下配置,生产环境下配置,测试环境下配置
spring.profiles.active=dev,表示激活application-dev.properties中的配置

编程方式设置激活配置的属性文件

package com.example.springbootstudy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class SpringbootStudyApplication {
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
    public static void main(String[] args) {
        SpringApplication application =new SpringApplication(SpringbootStudyApplication.class);
        application .run(args);
//  也可以通过ConfigurableEnvironment setActiveProfiles
        application.setAdditionalProfiles("dev");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值