为了方便多环境适配,springboot简化了profile功能。
1.1 application-profile功能
- 默认配置文件 application.yaml;任何时候都会加载,加载完后才继续加载指定配置文件
指定环境配置文件 application-{env}.yaml
spring.profiles.active=prod
激活指定环境
- 配置文件激活
- 命令行激活:java -jar xxx.jar —spring.profiles.active=prod —person.name=hao
- 修改配置文件的任意值,命令行优先
- 默认配置与环境配置同时生效
-
1.2 @Profile条件装配功能
使用@Profile注解可以根据加载的指定的配置文件去装配对应的类(也可以标在方法上)
@Profile("prod") @ConfigurationProperties("person") @Component @Data public class Boss implements Person{ private String name; private Integer age; }
@Profile("test") @ConfigurationProperties("person") @Component @Data public class Worker implements Person{ private String name; private Integer age; }
当加载application-prod.yaml时Boss类会被自动装配,而当加载application-test.yaml时Worker类会被装配
1.3 profile分组
spring.profiles.active=myprod
spring.profiles.group.myprod[0]=prod
spring.profiles.group.myprod[1]=test
使用分组可以指定多个配置文件一起生效