有的时候,我们需要判断当前的环境是开发环境还是测试 还是生产环境,然后写出相应的代码。
那下面的代码可以帮你做到,识别。
当然,我觉得您在看这篇文章的时候 一定是知道
如何使用spring.profiles.active 来无缝的切换正式环境和测试环境的配置。
的。
所以我们现在想要的结果就是:
我配置jvm启动参数的时候是
-Dspring.profiles.active="development"
那我输出的时候应该就是:
实现代码如下:
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()); }