Springboot 初始化之前获取启动环境参数

2020-11-10 / 191 阅读 / Java

虽然环境参数可以通过Springboot内置的Environment获取,但偶尔希望在初始化之前就知道将要运行的环境。因为配置active的方式很多,有跟在jar后面、系统的环境变量、配置文件等多渠道。其中只会有一种配置生效,因此还需要了解这些配置之间的加载优先级关系。

以下整理的常用的获取,从优先级最高逐级递减。实际还有多种方式,但目前未遇到,暂不整理。

public static String getActive(String[] args) {//args为应用启动时的参数
        String active = "";
        // 1命令行环境  --spring.profiles.active=dev
        Pattern compile = Pattern.compile("--spring\\.profiles\\.active=(.*)");
        for (String arg : args) {
            Matcher matcher = compile.matcher(arg);
            if (matcher.find()) {
                active = matcher.group(1);
            }
        }
        if (StringUtil.isNotEmpty(active)) {
            return active;
        }

        // 2Java系统属性 -Dspring.profiles.active=dev
        active = System.getProperty("spring.profiles.active");
        if (StringUtil.isNotEmpty(active)) {
            return active;
        }

        // 3操作系统环境变量 SPRING_PROFILES_ACTIVE=dev
        active = System.getenv("SPRING_PROFILES_ACTIVE");
        if (StringUtil.isNotEmpty(active)) {
            return active;
        }

        // 4配置文件 spring.profiles.active=dev
        active = PropertiesUtil.getProp("application.properties", "spring.profiles.active", "");
        return active;
    }
相关推荐