获取Spring中的activeProfile参数来判断当前运行环境

有的时候,我们需要判断当前的环境是开发环境还是测试 还是生产环境,然后写出相应的代码。那下面的代码可以帮你做到,识别。当然,我觉得您在看这篇文章的时候 一定是知道如何使用spring.profi...

有的时候,我们需要判断当前的环境是开发环境还是测试 还是生产环境,然后写出相应的代码。

那下面的代码可以帮你做到,识别。

当然,我觉得您在看这篇文章的时候 一定是知道

如何使用spring.profiles.active 来无缝的切换正式环境和测试环境的配置。

的。

所以我们现在想要的结果就是:

我配置jvm启动参数的时候是

-Dspring.profiles.active="development"

image.png

那我输出的时候应该就是:

image.png

实现代码如下:

package com.gb.pay.common.core;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.gb.pay.common.util.BeanUtil;

/**
 * @author Created by 
 * www.hellojava.com
 * © All Rights Reserved.
 */

@Component
public class ApplicationContextAwareImpl implements ApplicationContextAware {


    @Override
    public void setApplicationContext( ApplicationContext applicationContext) throws BeansException {
        log.info("应用程序上下文 : [{}]", "开始初始化");
        String activeProfile =  applicationContext.getEnvironment().getActiveProfiles()[0];
        System.out.println("active_profile:"+activeProfile);

        log.info("应用程序上下文 : [{}]", "初始化完成");
    }
    Logger log = LoggerFactory.getLogger(this.getClass());
}


  • 发表于 2019-04-02 16:26
  • 阅读 ( 2263 )
  • 分类:J2EE框架

条评论

请先 登录 后评论
不写代码的码农
三叔

422 篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除