项目高级配置
▶ 临时属性设置
▶ 配置文件分类
▶ 自定义配置文件
临时属性设置
● 带属性数启动SpringBoot
● 携带多个属性启动SpringBoot,属性间使用空格分隔
● 属性加载优先顺序
1.参看:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
临时属性设置(开发环境)
● 带属性启动SpringBoot程序,为程序添加运行属性
● 通过编程形式带参数启动SpringBoot程序,为程序添加运行参数
public static void main(String[] args) {
String[] arg = new String[1];
arg[0] ="--server.port=8082";
SpringApplication.run(SSMPApplication.class, arg);
}
● 不携带参数启动SpringBoot程序
SpringApplication.run(SSMPApplication.class);
配置文件分类
●.SpringBoot中4级配置文件
1级: file :config/application.yml 【最高】
2级: file :application.yml
3级:classpath:config/application.yml
4级:classpath:application.yml 【最低】
● 作用:
◆ 1级与2级留做系统打包后设置通用属性,1级常用于运维经理进行线上整体项目部署方案调控
◆ 3级与4级用于系统开发阶段设置通用属性,3级常用于项目经理进行整体项目属性调控
● 通过启动参数加载配置文件(无需书写配置文件扩展名)
注意:properties与yml文件格式均支持
● 多个属性配置先执行后面的属性配置
自定义配置文件——重要说明
● 单服务器项目:使用自定义配置文件需求较低
● 多服务器项目:使用自定义配置文件需求较高,将所有配置放置在一个目录中,统一管理
● 基于SpringCloud技术,所有的服务器将不再设置配置文件,而是通过配置中心进行设定,动态加载配置信息
多环境开发
• 多环境开发(YAML版)
• 多环境开发(Properties版)
• 多环境开发控制
多环境开发(YAML版)多配置文件格式
1.主启动配置文件application.yml
# 应用环境
# 公共环境
spring:
profiles:
active: test
2.环境分类配置文件application-pro.yml
server:
port: 8080
3.环境分类配置文件application-dev.yml
server:
port: 8081
4.环境分类配置文件application-test.yml
server:
port: 8082
技巧1:
● 主配置文件中设置公共配置(全局)
● 环境分类配置文件中常用于设置冲突属性(局部)
多环境开发(Properties版)多配置文件格式
● 主启动配置文件application.properties
spring.profiles.active=pro
● 环境分类配置文件application-pro.properties
server.port=80
● 环境分类配置文件application-dev.properties
server.port=81
● 环境分类配置文件application-test.properties
server.port=82
技巧2:
●根据功能对配置文件中的信息进行拆分,并制作成独立的配置文件,命名规则如下
◆ application-devDB.yml
◆ application-devRedis.yml
◆ application-devMVC.yml
● 使用include属性在激活指定环境的情况下,同时对多个环境进行加载使其生效,多个环境间使用逗号分隔
spring:
profiles:
active: dev
include: devDB,devMVC
注意:
当主环境dev与其他环境有相同属性时,主环境属性生效;其他环境中有相同属性时,最后加载的环境属性生效
技巧3:
● 从Spring2.4版开始使用group属性替代include属性,降低了配置书写量
● 使用group属性定义多种主环境与子环境的包含关系
spring:
profiles:
active: dev
group:
"dev": devDB,devRedis,devMVC
"pro": proDB,proRedis,proMVC
"test": testDB,testRedis,testMVC
多环境并发控制
● Maven与SpringBoot多环境兼容
①:Maven中设置多环境属性
<profiles>
<profile>
<id>dev_env</id>
<properties>
<profile.active>dev</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>pro_env</id>
<properties>
<profile.active>pro</profile.active>
</properties>
</profile>
<profile>
<id>test_env</id>
<properties>
<profile.active>test</profile.active>
</properties>
</profile>
</profiles>
②:SpringBoot中引用Maven属性
spring:
profiles:
active: @profile.active@
③:执行Maven打包指令,并在生成的boot打包文件.jar文件中查看对应信息