【业务功能篇79】Springboot获取多环境工具类

 SpringBeanUtils 工具类


package com.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * SpringBeanUtils
 * 
 */
@Component
public class SpringBeanUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;


    /**
     * setApplicationContext
     * 
     * @param applicationContext applicationContext
     * @throws BeansException BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBeanUtils.applicationContext == null) {
            SpringBeanUtils.applicationContext = applicationContext;
        }
    }


    /**
     * getApplicationContext
     * 
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }


    /**
     * getBean
     * 
     * @param name name
     * @return Object
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }


    /**
     * getBean
     * 
     * @param clazz clazz
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }


    /**
     * getBean
     * 
     * @param name name
     * @param clazz clazz
     * @return T
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }


    /**
     * getActiveProfile
     * 
     * @return String
     */
    public static String getActiveProfile() {
        return getApplicationContext().getEnvironment().getActiveProfiles()[0];
    }


    /**
     * isTestProfile
     * 
     * @return boolean
     */
    public static boolean isTestProfile() {
        return !Objects.equals(getActiveProfile(), "prod");
    }
}

业务层调用

一般都会区别测试环境,开发环境,生产环境,测试与开发环境一般就是本地了,那么为什么需要区分呢,比如有些调用发送推送信息功能,在测试环境下,我们可以发送给开发人员自测,而生产环境下,就是正常的发送给指定的业务人员,所以可以通过获取当前配置文件所指定的环境值变量,程序在本地跑起来的时候,我们可以设定为测试环境,自测用例就用来区分生产环境时所用的一些调用了。

   String env = SpringBeanUtils.getActiveProfile();
   String jumpUrl = env.equals("test") ? "测试" : "非测试";

环境值获取

  • 就是在我们appilcation.yml中配置
  • 项目配置文件,会根据这个active属性值,去获取对应的环境,执行对应的环境配置文件
  • 比如test,那么就会去获取application-test.yml,还有application-prod.yml,application-dev.yml
spring: 
  profiles:
    active: test

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值