Spring Boot 基础(二)Profiles

1,714 阅读1分钟

Profiles 是 Spring 框架的核心特性,表示一个“环境”的概念,允许开发者将 bean 映射到不同的环境中,然后在不同的环境下激活不同的 Profile 以保证只启动需要的 bean。

环境配置

假设工作环境有三种:dev(开发)、test(测试)、prod(生产),可以添加 4 个配置文件:

  • application.properties(公共配置)
  • application-dev.properties
  • application-test.properties
  • application-prod.properties 在公共配置application.properties文件中可以通过设置spring.profiles.active值来激活对应的 profile,如:
spring.profiles.active = dev

如果使用 YAML 配置文件,则对应的配置为:

spring:
  profiles:
    active: dev

YAML 配置也可以在一个文件中完成所有 profile 配置,不同的 profile 间使用---分隔,如:

spring:
  profiles:
    active: dev
---
spring:
  profiles: dev
  # 配置(略)
---
spring:
  profiles: test
  # 配置(略)
---
spring
  profiles: prod
  # 配置(略)

@Profile

使用@Profile注解指定 bean 在特定的 profile 环境中生效,如果定义一个 bean 只在开发环境中激活,而不会部署在生产环境中,则可以定义如下:

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

如果一个 bean 在除开发环境外的其它环境中都应该是激活的,则可以使用如下定义:

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

@Profile注解也可以作用在方法上。

激活 Profile

1. jar 激活

java -jar -Dspring.profiles.active=prod *.jar

2. 代码设置环境变量

System.setProperty("spring.profiles.active", "prod");

3. Spring 容器中激活

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("prod");
ctx.register(XxxConfig.class);
ctx.refresh();