cn.meteor.common.launch.MeteorApplication Maven / Gradle / Ivy
package cn.meteor.common.launch;// Copyright (C), Created on 2021-04-02
import cn.meteor.common.launch.constants.AppConstants;
import cn.meteor.common.launch.constants.BootConstants;
import cn.meteor.common.launch.constants.EnvConstants;
import cn.meteor.common.launch.service.LauncherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.*;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 流星启动器
*
* 赋予默认配置环境、减少环境配置文件体积
*
* @author ths
* @since 1.0.0
*/
@Slf4j
public class MeteorApplication {
/**
* Create an application context
* java -jar app.jar --spring.profiles.active=dev --server.port=8080
*
* @param appName application name
* @param source The sources
* @param args args
* @return an application context created from the current state
*/
public static ConfigurableApplicationContext run(String appName, Class> source, String... args) {
SpringApplicationBuilder builder = createSpringApplicationBuilder(appName, source, args);
return builder.run(args);
}
public static SpringApplicationBuilder createSpringApplicationBuilder(String appName, Class> source, String... args) {
Assert.hasText(appName, "[appName]服务名不能为空");
// 读取环境变量,使用spring boot的规则
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addFirst(new SimpleCommandLinePropertySource(args));
propertySources.addLast(new MapPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, environment.getSystemProperties()));
propertySources.addLast(new SystemEnvironmentPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, environment.getSystemEnvironment()));
// 获取配置的环境变量
String[] activeProfiles = environment.getActiveProfiles();
// 判断环境: dev、test、prod
List profiles = Arrays.asList(activeProfiles);
// 预设的环境
List presetProfiles = new ArrayList<>(Arrays.asList(EnvConstants.DEV, EnvConstants.TEST, EnvConstants.PROD));
// 交集
boolean b = presetProfiles.retainAll(profiles);
// 当前使用
List activeProfileList = new ArrayList<>(profiles);
if (b) {
activeProfileList = new ArrayList<>(presetProfiles);
}
Function