| 当我们的项目部署到线上之后,部署环境和开发环境不同,这时可写多个配置文件,在不同的环境指定不同的配置文件 |
| |
| 例如用于默认,生产,测试环境的配置文件: |
| application.properties application-prod.yaml application-test.yaml |
| |
| 我们在默认配置文件中指定使用哪个配置文件,application.properties中配置:spring.profiles.active=prod |
| |
| 在默认配置文件中未指定则使用默认环境 |
| |
| 若默认配置和生产配置同时指定了端口号,且默认配置中指定了生产配置环境,这时默认配置和生产配置同时生效,且生产配置优先 |
| 当我们的项目打成jar包后,在cmd使用命令激活:java -jar jar名称 --配置文件中的属性 |
| |
| java -jar xxx.jar --spring.profiles.active=prod --person.name=haha |
| |
| 在cmd使用命令可修改任意配置,且使用命令修改的属性配置优先级高于配置文件配置;也即是说,在配置文件配置后,最后在命令行配置,以命令行的配置为准 |
| # 当我们在类或配置类上使用该注解,表示在哪种环境下生效:@Profile("prod") |
| |
| # 案例1 |
| @Profile("test") |
| @Component |
| @ConfigurationProperties("person") |
| @Data |
| public class Worker implements Person { |
| |
| private String name; |
| private Integer age; |
| } |
| |
| # 案例2 |
| @Profile(value = {"prod","default"}) |
| @Component |
| @ConfigurationProperties("person") |
| @Data |
| public class Boss implements Person { |
| |
| private String name; |
| private Integer age; |
| |
| } |
| |
| @Configuration |
| public class MyConfig { |
| |
| @Profile("prod") |
| @Bean |
| public Color red(){ |
| return new Color(); |
| } |
| |
| @Profile("test") |
| @Bean |
| public Color green(){ |
| return new Color(); |
| } |
| } |
| # 我们可在默认配置文件中将多个配置文件分为一组,这样即可同时激活多个环境 |
| # 如下为默认配置文件,配置如下 |
| spring.profiles.active=myprod # 将以下两个环境分为一组,再激活这个组 |
| spring.profiles.group.myprod[0]=ppd |
| spring.profiles.group.myprod[0]=test |
| spring.profiles.group.myprod[1]=prod |
| # 这时打包的jar会使用ppd和test环境 |
| |
| # 方式2,使用命令激活当前这个组 |
| --spring.profiles.active=myprod |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?