fix: 修复框架启动逻辑导致spring boot多profiles功能不可用的问题

# 问题描述
框架在检测应用启动设置的profiles时,本意为不允许指定多个环境,即不可同时指定dev、test、prod中的两个或三个,最多只允许使用其中一个。但具体实现却是不允许指定多个profile,即便不是表示环境的profile也不允许存在多个。这就导致本来spring boot所具有的同时激活多个profile的功能不可用了,与spring boot框架冲突。

# 解决方案
检测应用所设置profiles时,只要求不能使用dev、test、prod的多个,其它profile允许多个。比如`spring.profiles.active=dev,mysql,redis`

Signed-off-by: tangjl <tangjiali5@163.com>
This commit is contained in:
tangjl 2023-07-07 12:45:07 +00:00 committed by Gitee
parent 0885b48ad9
commit b6e6cc2724
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

View File

@ -65,24 +65,26 @@ public class BladeApplication {
List<String> presetProfiles = new ArrayList<>(Arrays.asList(AppConstant.DEV_CODE, AppConstant.TEST_CODE, AppConstant.PROD_CODE));
// 交集
presetProfiles.retainAll(profiles);
// 当前使用
List<String> activeProfileList = new ArrayList<>(profiles);
Function<Object[], String> joinFun = StringUtils::arrayToCommaDelimitedString;
SpringApplicationBuilder builder = new SpringApplicationBuilder(source);
String profile;
if (activeProfileList.isEmpty()) {
// 默认dev开发
if(presetProfiles.isEmpty()){
// 未指定环境默认dev
profile = AppConstant.DEV_CODE;
activeProfileList.add(profile);
builder.profiles(profile);
} else if (activeProfileList.size() == 1) {
profile = activeProfileList.get(0);
profiles.add(profile);
} else if (presetProfiles.size() == 1) {
// 已指定唯一环境
profile = presetProfiles.get(0);
} else {
// 同时存在devtestprod环境时
throw new RuntimeException("同时存在环境变量:[" + StringUtils.arrayToCommaDelimitedString(activeProfiles) + "]");
throw new RuntimeException("同时存在环境变量:[" + joinFun.apply(presetProfiles.toArray()) + "]");
}
// 设置激活的Profile
SpringApplicationBuilder builder = new SpringApplicationBuilder(source);
builder.profiles(presetProfiles.toArray(new String[presetProfiles.size()]));
String startJarPath = BladeApplication.class.getResource("/").getPath().split("!")[0];
String activePros = joinFun.apply(activeProfileList.toArray());
String activePros = joinFun.apply(profiles.toArray());
System.out.println(String.format("----启动中,读取到的环境变量:[%s]jar地址:[%s]----", activePros, startJarPath));
Properties props = System.getProperties();
props.setProperty("spring.application.name", appName);
@ -102,7 +104,8 @@ public class BladeApplication {
// 加载自定义组件
List<LauncherService> launcherList = new ArrayList<>();
ServiceLoader.load(LauncherService.class).forEach(launcherList::add);
launcherList.stream().sorted(Comparator.comparing(LauncherService::getOrder)).collect(Collectors.toList())
launcherList.stream()
.sorted(Comparator.comparing(LauncherService::getOrder))
.forEach(launcherService -> launcherService.launcher(builder, appName, profile));
return builder;
}