SpringBoot项⽬在多环境下(开发、⽣产或测试环境)调⽤不
同配置⽂件⽅式
写在前⾯spring怎么读取properties
  最近由于项⽬要求,原先的项⽬只有开发环境的项⽬配置,后来不利于线上测试,于是,最近对于SpringBoot这部分多环境配置在⽹上查了相关资料,并实现了配置,于是为了防⽌遗忘,特在此进⾏总结。
  好啦,废话不多说,开启正⽂(好像很正式的样⼦呢。。。。。。)
SpringBoot多环境配置⽂件
下⾯以⼀个⼩案例,进⾏说明。
如图所⽰,下图是案例中的三个配置⽂件,其中,
对于,dev和prod这两个⽂件在启动服务时,服务器不会⾃动加载,那么在不同的环境中时怎么调⽤不同的⽂件的呢?
主要有以下两种⽅式:
⽅式⼀:通过修改配置⽂件 l中Spring.profile.active的值,来指定加载的配置,
也就是说,如果Spring.proflie.active=dev,则在启动服务之后,服务器就会加载l,若值为test或者prod,修改⽅式⼀致。
下⾯上图说明:
⽅式⼆:使⽤命令启动服务,命令中带参数⽅式(此⽅式可以没有l⽂件)
具体操作步骤如下:
1>  进⼊到项⽬⽬录下,先⽤mvn install命令对项⽬进⾏打包,执⾏完此步骤后,会在项⽬对应的target⽬录下⽣成该项⽬对应的jar包
2>  进⼊target⽬录,执⾏命令:java -jar ⽣成的jar包 --spring.profiles.active=prod
通过此命令之后,项⽬就会调⽤l配置⽂件,即以⽣产环境的配置要求启动服务。同理,若是开发环境,只需将prod改为dev即可。
⽅式三:此种⽅式是根据⽅式⼀延伸出的,更为灵活
具体步骤如下:
1> l中将spring.profiles.active的值改成spring.profiles.active=@activatedProperties@,这⾥的@activatedProperties@是⼀个变量对应pom⽂件⾥的环境配置。
下⾯为pom⽂件的配置<profiles>  <profile>
<id>dev</id>
<properties>
<!-- 环境标识,需要与配置⽂件的名称相对应 -->
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<!-- 默认环境 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
                   <!-- 测试环境 --> 
<activatedProperties>test</activatedProperties>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
                   <!-- ⽣产环境 -->
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles> 
对这段代码做下说明: 
⾸先在maven中配置了两个环境的配置⽂件,⼀个测试环境test,⼀个⽣产环境prod;
其中
<profiles.active></profiles.active>  是变量的key,test是变量的value
注意:<activatedProperties>dev</activatedProperties>中的dev与配置⽂件名称l要⼀致
activatedProperties名称对应application.properties配置⽂件中的spring.profiles.active=@activatedProperties@
当maven打包时会⽤pom⽂件⾥<activatedProperties>dev</activatedProperties>中的值替换掉application.properties配置⽂件中的
@activatedProperties@
2>  执⾏Maven打包命令mvn clean package,观察控制台⽇志
已经构建成功,刷新⼀下项⽬,target会⽣成SpringbootMybatis-0.0.1-SNAPSHOT.jar包。
可能出现的问题
1.=='@' that cannot start any token. (Do not use @ for indentation)
在本地启动该项⽬时有时候会报如下错误
found character '@' that cannot start any token. (Do not use @ for indentation)
in 'reader', line 4, column 11:
意思是识别不了@profiles.active@这个变量,这是因为这个变量没有被替换成我们需要的参数,如test,prod等,所以在本地启动时要加上参数启动,这样springboot会⾃动替换掉这个变量。
作者使⽤的是idea,所以启动springboot时在右上Edit Configurations-->Active Profiles 增加⼀个参数,参数值为你需要运⾏的环境名称,如test
注:上述中的l、l等只是演⽰案例中名字,并⾮所有项⽬都是如此,还请各位以实际项⽬为主。
在此,感谢以下博主的⽂章:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。