• 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”这个结果。

  • 相关阅读:
    mysql数据库表名区分大小写
    Maven配置和使用
    Centos7修改网卡名称
    mongo启动报错问题处理
    zabbix分布式部署和主机自动发现
    zabbix-server、proxy、agent的分布式部署步骤
    zabbix常见错误处理方式
    git用ssh方式下载和提交代码
    CentOS7使用阿里云的yum源
    VMware三种网络模式详解
  • 原文地址:https://www.cnblogs.com/woyujiezhen/p/13363886.html
Copyright © 2020-2023  润新知