Env获取运行时环境

Env工具类获取运行时环境

public class EnvConfig {

    public enum Env {

        PROD("prod","PROD","生产环境"),
        UAT("uat","UAT","预发环境"),
        DEV("dev","DEV","开发环境");
        private String code;
        private String enMsg;
        private String zhMsg;
        Env(String code,String enMsg,String zhMsg){
            this.code = code;
            this.enMsg = enMsg;
            this.zhMsg = zhMsg;
        }
    }
    public static Env getEnv() {
        return Env.valueOf(BeanContext.getApplicationContext().getEnvironment().getActiveProfiles()[0].toUpperCase(Locale.ROOT));
    }

    public static String getEnvDesc(){
        return getEnv().enMsg;
    }

}

依赖的BeanContext上下文定义

@Configuration
public class BeanContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContext.applicationContext = applicationContext;
    }
}
posted @ 2023-06-26 14:13  SpecialSpeculator  阅读(29)  评论(0编辑  收藏  举报