一、原理:

  1、实现ApplicationContextAware(当一个类实现了ApplicationContextAware这个接口之后,这个类就可以通过setApplicationContext方法获得ApplicationContext中的上下文),获取context。通过方法:context.getEnvironment().getActiveProfiles()获取激活的profile。

  2、通过service中成员变量上的注解:@Value("${spring.profiles.active}"),获取yaml中的profile

二、上代码:

通过context获取:

package com.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service; @Service
public class SpringContextUtil implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SpringContextUtil.class); private static final String PRODUCTION_PROFILE = "production";
private static final String STAGE_PROFILE = "stage"; private static ApplicationContext context = null; public static <T> T getBean(String beanName) {
return (T) context.getBean(beanName);
} public static String[] getActiveProfileList() {
return context.getEnvironment().getActiveProfiles();
} /**
* 判断当前环境是否是线上环境:production或stage
* @return
*/
public static boolean isProfileActived() {
String[] profiles = context.getEnvironment().getActiveProfiles();
if (profiles == null || profiles.length == 0) {
return false;
}
for (String val : profiles) {
logger.info("current profile from context is: {}", val);
if (val.equalsIgnoreCase(PRODUCTION_PROFILE) || val.equalsIgnoreCase(STAGE_PROFILE)) {
return true;
}
}
return false;
} @Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.context = applicationContext;
} }

通过yaml(或properties)文件获取

package com.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; @Service
public class SpringProfileService {
private static final Logger logger = LoggerFactory.getLogger(SpringProfileService.class); private static final String PRODUCTION_PROFILE = "production";
private static final String STAGE_PROFILE = "stage"; @Value("${spring.profiles.active}")
private String profile; public boolean isProfileActived() {
logger.info("current profile from yaml is: {}", profile);
if (profile.equalsIgnoreCase(PRODUCTION_PROFILE) || profile.equalsIgnoreCase(STAGE_PROFILE)) {
return true;
}
return false;
}
}

单元测试代码:

package com.**.service;

import com.**.Application;
import com.test.SpringContextUtil;
import com.test.SpringProfileService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ServiceTest {
private static final Logger logger = LoggerFactory.getLogger(ServiceTest.class); @Test
public void test1() {
Boolean actived = SpringContextUtil.isProfileActived();
logger.info(actived.toString());
} @Autowired
SpringProfileService springProfileService; @Test
public void test2() {
Boolean actived = springProfileService.isProfileActived();
logger.info(actived.toString());
}
}

其他。pom的相关配置截图,yaml的相关配置截图

spring&pom两种获取profile的方式的更多相关文章

  1. 两种获取connectionString的方式

    两种获取connectionString的方式 1. public static string connectionString = ConfigurationManager.ConnectionSt ...

  2. Hibernate中两种获取Session的方式

    转自:https://www.jb51.net/article/130309.htm Session:是应用程序与数据库之间的一个会话,是hibernate运作的中心,持久层操作的基础.对象的生命周期 ...

  3. Spring两种实现AOP的方式

    有两种实现AOP的方式:xml配置文件的方式和注解的形式 我们知道通知Advice是指对拦截到的方法做什么事,可以细分为 前置通知:方法执行之前执行的行为. 后置通知:方法执行之后执行的行为. 异常通 ...

  4. struts2和spring的两种整合方式

    首先,来看看如何让Spring 来管理Action. 在struts.xml中加入 <constant name="struts.objectFactory" value=& ...

  5. 流式思想概述和两种获取Stream流的方式

    流式思想概述 整体来看,流式思想类似于工厂车间的生产流水线 当需要对多个元素进行操作(特别是多步操作)的时候,考虑到性能及便利性,我们应该首先拼好一个模型步骤方案,然后再按照方法去执行他 这张图中展示 ...

  6. Spring中三种配置Bean的方式

    Spring中三种配置Bean的方式分别是: 基于XML的配置方式 基于注解的配置方式 基于Java类的配置方式 一.基于XML的配置 这个很简单,所以如何使用就略掉. 二.基于注解的配置 Sprin ...

  7. Request三种获取数据的方式

    今天在做ajax请求后台代码时,发现ajax的方法都对,但就是请求不了后台代码,后来在同事帮助下才发现前台定义了两个相同参数导致请求出错. 下面记录一下request三种获取数据的方式: 1. Req ...

  8. flask框架--设置配置文件的几种方式 与Flask两种配置路由的方式

    设置配置文件的几种方式 ==========方式一:============ app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #这种方式要把所 ...

  9. OC中两种单例实现方式

    OC中两种单例实现方式 写在前面 前两天探索了一下C++ 的单例,领悟深刻了许多.今天来看看OC中的单例又是怎么回事.查看相关资料,发现在OC中一般有两种实现单例的方式,一种方式是跟C++ 中类似的常 ...

随机推荐

  1. 在<a></a>标签中如何调用javaScript脚本

    在日常工作总会遇到在<a>标签中执行js代码的情况 现在做一个总结,希望对大家有一个帮助. 1.a href="javascript:js_method();" 这是我 ...

  2. 《JS权威指南学习总结--第7章 数组概念、稀疏数组》

    一.数组概念 数组是值的有序结合.每个值叫做一个元素,而每个元素在数组中都有一个位置,用数字表示,称为索引. JS数组是无类型的:数组元素可以是任意对象,并且同一个数组中的不同元素也可能有不同的类型. ...

  3. jdbc预编译实现方式

    jdbc预编译可以有两种方式: 方式一.jdbc自己实现的预编译,就是做一下特殊字符处理来防SQL注入,看PreparedStatement源码就可以了. public static void mai ...

  4. datagrid相关

    int rowID = Convert.ToInt32(dataGrid_OpenBoxScan.CurrentRowIndex.ToString());//得到所选行的行号              ...

  5. 基于Redisson+SpringBoot的Redission分布式锁

    原文:https://blog.csdn.net/sunct/article/details/80178197 定义分布式锁接口 package com.redis.lock.redisson_spr ...

  6. JavaScript-前言

    目录 前言 前言 这是针对纯小白的Javascript教程. 有人问我,网页中流行的脚本语言是什么?这个时候我会简单粗暴的说:只有Javascript!对,只有Javascript.Javascrip ...

  7. 缓存中,2个注解:@cacheable 与 @cacheput 的区别

    @cacheable:只会执行一次,当标记在一个方法上时表示该方法是支持缓存的,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果. @cac ...

  8. turtle模块

    turtle(海龟)绘图用法 import turtle -->调出turtle库 setup()-->设置窗体大小和位置 turtle.setup(width,height,startx ...

  9. volatile 关键字 和 i++ 原子性

    package com.mozq.multithread; /** * 深入理解Java虚拟机 volatile 关键字 和 i++ 原子性. */ public class VolatileTest ...

  10. 树莓派项目(1-3 )目标识别 NNPACK支持版Darknet,可用于树莓派等嵌入设备

    https://github.com/digitalbrain79/darknet-nnpack https://github.com/AlexeyAB/darknet#how-to-train-to ...