SpringBoot中获取spring.profiles.active的值

一、网上很多采用@Profile("dev")的方式获取,但是这个是类级别的

二、开发中可能需要代码级别

1、刚开始我想通过classpath下的文件读取方式,麻烦死了,于是换了个思路。

2、SpringBoot启动日志中有下面这句:

15:57:56.128 [restartedMain] INFO  c.d.o.OptplatformApplication - The following profiles are active: test

(1)跟踪代码:SpringApplication.run方法

public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		FailureAnalyzers analyzers = null;
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
					args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners,
					applicationArguments);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			analyzers = new FailureAnalyzers(context);
			prepareContext(context, environment, listeners, applicationArguments,
					printedBanner);  // 在这里打印了,跟踪进去
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			listeners.finished(context, null);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass)
						.logStarted(getApplicationLog(), stopWatch);
			}
			return context;
		}
		catch (Throwable ex) {
			handleRunFailure(context, listeners, analyzers, ex);
			throw new IllegalStateException(ex);
		}
	}

(2)跟踪代码:SpringApplication.prepareContext方法

private void prepareContext(ConfigurableApplicationContext context,
      ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
      ApplicationArguments applicationArguments, Banner printedBanner) {
   context.setEnvironment(environment);
   postProcessApplicationContext(context);
   applyInitializers(context);
   listeners.contextPrepared(context);
   if (this.logStartupInfo) {
      logStartupInfo(context.getParent() == null);
      logStartupProfileInfo(context);  // 名称很明显,继续跟踪进去
   }
   ......
}

(3)跟踪代码:SpringApplication.logStartupProfileInfo方法

protected void logStartupProfileInfo(ConfigurableApplicationContext context) {  
   Log log = getApplicationLog();
   if (log.isInfoEnabled()) {
      String[] activeProfiles = context.getEnvironment().getActiveProfiles();
      if (ObjectUtils.isEmpty(activeProfiles)) {
         String[] defaultProfiles = context.getEnvironment().getDefaultProfiles();
         log.info("No active profile set, falling back to default profiles: "
               + StringUtils.arrayToCommaDelimitedString(defaultProfiles));  
      }
      else {
         log.info("The following profiles are active: "
               + StringUtils.arrayToCommaDelimitedString(activeProfiles));  //找到了,很明显用了ApplicationContxt容器,接下来就是写个工具类来获取Application就行啦。

     } 
   } 
}

 (4)编写SpringContxtUtil工具类

/**
 * 项目名称:
 * 类名: SpringContextUtil
 * 描述: 获取bean的工具类,可用于在线程里面获取bean
 * 创建人: awsm
 * 创建时间: Dec 17, 2015 10:46:44 PM
 * 修改人:little evil
 * 修改时间:May 18, 2018 04:01:34 PM
 * 修改备注:添加getActiveProfile方法,获取当前环境
 * 版本:1.1
 */
@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];
    } 
}
// 该工具类从网上抄来的,最后添加个获取方法就完成了,这样就能在代码级别通过环境条件来控制方法行为了。

  

posted @ 2018-05-18 16:14  月下小魔王  阅读(47612)  评论(3编辑  收藏  举报