spring profiles 是 spring 提供的环境隔离机制,支持通过 @profile 注解、多文件命名约定(如 application-dev.properties)、编程式激活等方式,按 dev/test/prod 等环境自动加载对应配置和 bean,实现配置与组件的条件化注入。

Spring Profiles 是 Spring 提供的环境隔离机制,能让你根据运行环境(如 dev / test / prod)自动加载对应的配置,避免手动修改配置文件或硬编码判断。
1. 定义 Profile 并激活
Spring 通过 @Profile 注解标记哪些 Bean 或配置类只在特定环境下生效。激活方式有多种:
- 启动时通过 JVM 参数:
-Dspring.profiles.active=dev - 在
application.properties中设置:spring.profiles.active=prod - 代码中编程式激活:
ConfigurableEnvironment.setActiveProfiles("test") - 使用 Spring Boot 的
--spring.profiles.active=staging命令行参数
2. 按 Profile 切分配置文件
Spring Boot 默认支持按命名约定加载多环境配置:
-
application.properties:通用配置(所有环境共享) -
application-dev.properties:开发环境专用配置 -
application-prod.properties:生产环境专用配置 -
application-test.yml:也可用 YAML 格式,效果一致
只要激活了对应 profile,Spring Boot 就会自动合并加载 application.properties 和 application-{profile}.properties,后者优先级更高,可覆盖前者同名属性。
3. 使用 @Profile 控制 Bean 注入
当某些组件只应在特定环境存在时(例如开发用 H2 数据库、生产用 MySQL),可用 @Profile 注解:
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource h2DataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
@Profile("prod")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create()
.url("jdbc:mysql://prod-db:3306/myapp")
.username("root")
.password("123456")
.build();
}
}
这样,只有激活 dev 时才会创建 H2 数据源,prod 下则注入 MySQL 数据源,不会冲突也不会报错。
4. 条件化加载外部配置或属性源
除了配置文件和 Bean,你还可以按 profile 动态添加 @PropertySource:
@Configuration
@PropertySource(value = "classpath:config-${spring.profiles.active}.properties",
ignoreResourceNotFound = true)
public class CustomPropertyConfig { }
或者结合 @ConditionalOnProperty 实现更细粒度控制,比如仅当某 profile 激活且某个属性为 true 时才启用某个功能模块。
不复杂但容易忽略的是 profile 名称大小写敏感,推荐统一用小写;多个 profile 可用逗号分隔,如 dev,local,此时所有匹配的 profile 都会生效。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











