SpringBoot Profiles
官网地址
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");
}
}