SpringBoot构建微服务实战 之 Profile决策
在一个SpringBoot 项目中会使用不同环境的配置,在这里我们定义一些名词:
-
Intergration :个人开发集成环境
-
UAT:测试开发集成环境
-
Production:正式产品环境
现在有个场景:我们如何切换使用不同的配置以让我们的项目在指定的环境里运行呢?
即我想应用在 Intergration Evn中运行,那么此时项目读取的应该是 Intergration 的配置信息。
其实SpringBoot 为我们提供了一个 Profile 的决策即你可以让项目读取指定的配置文件信息。下面我们将以一个实例来说明。
-
在classpath下新建三个配置文件 application-Integration.properties(个人集成环境) 、 application-UAT.properties(测试集成环境 和 application.properties(默认为指定读取的配置文件,默认启用)
-
application-Integration.properties
Integration.url=127.0.0.1:3306///springBoot_Integration
-
application-UAT.properties
UAT.url=127.0.0.1:3306///springBoot_UAT
-
application.properties
default.url=127.0.0.1:3306///springBoot_default
-
-
App.java
@Configuration public class App { /** * 默认 配置生效时启用该Bean */ @Bean public Runnable defaultProfile() throws Exception{ System.out.println("DefaulProfile was setted up"); return () ->{}; } /** * Integration 配置生效时启用该Bean * * @return * @throws Exception */ @Bean @Profile("Integration") public Runnable integrationProfile() throws Exception{ System.out.println("integrationProfile was setted up"); return () ->{}; } /** * UAT 配置生效时启用该Bean * @return * @throws Exception */ @Bean @Profile("UAT") public Runnable uatProfile() throws Exception{ System.out.println("uatProfile was setted up"); return () ->{}; } public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); // 通过设置启动参数来设置生效的profile 即指定哪些配置文件生效,下面为一个激活多个profile 语句======================================================================= // --spring.profiles.active=UAT,Integration 前面两个横杆 // 单个的语句命令为:--spring.profiles.active=UAT System.out.println(context.getEnvironment().getProperty("UAT.url")); System.out.println(context.getEnvironment().getProperty("Integration.url")); System.out.println("ProfileConfiguration end line ==============================================================================="); //根据启用该不同的 profile 来执行不同的逻辑 } }
-
使用场景
-
同时启用Integration 和 UAT 两个环境配置
-
运行结果
-
小结
-
本节中实例中 使用 --spring.profiles.active=UAT,Integration 可以启用 UAT,Integration 两种配置,同时也可以启用其中的某一种:–spring.profiles.active=UAT/Integration。
-
本例子是在 Windows OS 下演示的,如果在Unix/Linux OS 下可以考虑进一步封装集成,即把启用的命令写进shell 脚本,以后我们只要运行相应的脚本即可将项目在指定的环境中运行。