spring.profiles.active在项目中获取参数

springboot请看这篇: https://blog.csdn.net/qq_34706514/article/details/115300654

<!-- 环境切换专用: dev 开发环境  test:测试环境  prod:正式环境 -->
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>

业务需要在项目中判断现在是哪套环境 然后处理不同的业务 花了半个小时搞定 分享一下 前提是已经配置了spring profiles

1.先创建个bean用来保存环境参数

/**
 * 单例存储系统当前环境
 */
public class ProfilesBean {

    //饿汉单例模式
    //在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快

    private static ProfilesBean profilesBean = new ProfilesBean();//静态私有成员,已初始化

    private String profiles;

    private ProfilesBean()
    {
        //私有构造函数
    }

    public static ProfilesBean getInstance()    //静态,不用同步(类加载时已初始化,不会有多线程的问题)
    {
        return profilesBean;
    }

    public String getProfiles() {
        return profiles;
    }

    public void setProfiles(String profiles) {
        this.profiles = profiles;
    }
}

2.在创建个监听器获取变量

port com.tonglifang.common.beans.ProfilesBean;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * 监听获取当前系统环境 dev test prod
 */
@WebListener
public class AppListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            ServletContext sc = sce.getServletContext();
            String profiles = sc.getInitParameter("spring.profiles.active");
            ProfilesBean profilesBean = ProfilesBean.getInstance();
            profilesBean.setProfiles(profiles);
        } catch(Exception e) {

        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

3.代码中使用

String profiles = ProfilesBean.getInstance().getProfiles();

这样就得到了现在系统跑的是哪套环境 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赛赛liangks

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值