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();
這樣就得到了現在系統跑的是哪套環境