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();
这样就得到了现在系统跑的是哪套环境