0
点赞
收藏
分享

微信扫一扫

7. SpringBoot — Profile

Profile 是什么?

我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml
但 默认使用application.properties/yml 的配置;

所以我们可以配置很多配置文件以 "application-XXX.properties/yml" 命名,例如:【下面以properties为例  yml也是可以的】

7. SpringBoot —  Profile_jar

 

 

 其中 ABC三个就是我自己创建的,你可以往里面写配置,但是不会生效,如果你想生效就得 激活:

 

 

激活配置文件

激活配置文件有很多种方法,其中分 properties 和 yml 的:

1.1 properties文件激活指定 profile:

激活方法1 【 在主配置类 application.properties 上写语句】

7. SpringBoot —  Profile_jar_02

 

现在三个文件 A、B、C 分别设置了  端口 8097、8098、8099

首先我们知道,不管你配多少个 他都是冲 application.properties 入口的,我们在里面直接写语句激活某个文件即可:

 7. SpringBoot —  Profile_spring_03

 

激活语句貌似只能写一个 我写多了直接报错了。 

然后运行可以看到端口改到了 8097

7. SpringBoot —  Profile_配置文件_04

 

 这就是第一种激活方法。

 

激活方法2 【随启动命令行激活指定  profile】

7. SpringBoot —  Profile_配置文件_05

 

 然后:

7. SpringBoot —  Profile_配置文件_06

 

 可以看到 设置这个profile,我们这里是激活B,运行:

7. SpringBoot —  Profile_spring_07

 

 端口号成功改为了 8098  就是B的配置。

 

 

激活方法3 【打包后 启动的时候 添加命令行 激活指定profile】

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=C
可以直接在测试的时候,配置传入命令行参数

例:7. SpringBoot —  Profile_配置文件_08  这里激活的是 C propertoes文件

 

 运行可以看到:

7. SpringBoot —  Profile_spring_09

 其实就是允许这个jar 然后最后后面加个

--spring.profiles.active=XXX

所以你看配置文件C 那个 properties 文件生效了 ,,,,  端口变8099了。

 

激活方法4 【虚拟机参数中写语句 ;  这里示例激活 B文件】

 7. SpringBoot —  Profile_jar_10

 7. SpringBoot —  Profile_jar_11

 运行:

7. SpringBoot —  Profile_spring_12

 端口变8098 即B文件那个。

1.2 yml文件激活指定 profile:

 

如果你写的配置文件是 yml,那么我推荐你别写多个yml,因为yml支持多文档块方式激活指定profile:

-

三个减号代表 分块,即配置分块,所以你直接在总那个yml写即可、

7. SpringBoot —  Profile_配置文件_13

 

 可以清楚看到 分快了。这些快代表可以写不同配置 ,独立的。

 

如果这样写:

7. SpringBoot —  Profile_spring_14

 

 

完全可以看到 其实那个也一样是那条语句   spring.profiles.active=XXX    

我们运行:

7. SpringBoot —  Profile_spring_15

 

 果然变成了 8099 端口,这就是 yml 激活 profile 的方法。

 

总结:

这里说了很多 properties激活指定profile方法  和 yml的莹说了,但是 推荐你自己用一总即可,其次呢 这些一般都是测试开发的时候些的,

其实这里面存在优先级,所以叫你选一中即可。

 


作者:咸瑜


举报

相关推荐

0 条评论