zoukankan      html  css  js  c++  java
  • Spring Boot获取spring.profiles.active:dev的值,也就是获取当前运行的环境配置

    这个spring.profiles.active的值虽然是可以通过@Value注解之类的方式获取到,但如果需要获取这个值的类是不被spring管理的呢?那就不能直接用过spring boot的简单注解方式直接获取值了,然后最近找到一个这个类。

    @Component
    public class SpringContextUtil implements ApplicationContextAware {
    
        private static ApplicationContext context = null;
    
        /* (non Javadoc)
         * @Title: setApplicationContext
         * @Description: spring获取bean工具类
         * @param applicationContext
         * @throws BeansException
         * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
         */
        @Override
        public void setApplicationContext(ApplicationContext applicationContext)
                throws BeansException {
            this.context = applicationContext;
        }
    
        // 传入线程中
        public static <T> T getBean(String beanName) {
            return (T) context.getBean(beanName);
        }
    
        // 国际化使用
        public static String getMessage(String key) {
            return context.getMessage(key, null, Locale.getDefault());
        }
    
        /// 获取当前环境
        public static String getActiveProfile() {
            return context.getEnvironment().getActiveProfiles()[0];
        }
    }

    可以在类加载完成后(也就是说需要注意使用的时间,这个结果是否正常返回了值)通过SpringContextUtil.getActiveProfile来获取到spring.profiles.active=dev中的“dev”这个结果。

  • 相关阅读:
    codeforces 632F. Magic Matrix
    codeforces 632D. Longest Subsequence 筛法
    移动端项目开发需要注意的问题
    input框、按钮组间的去除空格的解决方案
    radio 和checkbox与文字对齐问题
    怎样设置webstorm localhost为本地ip
    The number of steps(概率dp)
    C++ 面试常见问题
    禅者初心
    Hope
  • 原文地址:https://www.cnblogs.com/woyujiezhen/p/13363886.html
Copyright © 2011-2022 走看看