SpringBoot中获取spring.profiles.active的值

转载:https://www.cnblogs.com/linzhanfly/p/9056722.html

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

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

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

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

1

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

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方法

1

2

3

4

5

6

7

8

9

10

11

12

13

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方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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工具类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

/**

 * 项目名称:

 * 类名: 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];

    }

}

// 该工具类从网上抄来的,最后添加个获取方法就完成了,这样就能在代码级别通过环境条件来控制方法行为了。

  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值