1. 程式人生 > >springMVC的多環境配置_基於springprofile

springMVC的多環境配置_基於springprofile

記錄一下springMVC專案的多環境的切換。基於springprofile。

一 簡單實現

     1 首先將配置檔案進行分離,分成development(本地環境)、test(測試環境)、production(正式環境) 

配置檔案目錄如下

common目錄用來存放一些每個環境下都一樣的配置檔案

2 配置spring和springmvc配置檔案最下面配置如下beans

<!-- 開發環境配置檔案 -->
<beans profile="development">
    <context:property-placeholder
            location="classpath*:config_common/*.properties, classpath*:config_development/*.properties"/>
</beans>

<!-- 測試環境配置檔案 -->
<beans profile="test">
    <context:property-placeholder
            location="classpath*:config_common/*.properties, classpath*:config_test/*.properties"/>
</beans>

<!-- 生產環境配置檔案 -->
<beans profile="production">
    <context:property-placeholder
            location="classpath*:config_common/*.properties, classpath*:config_production/*.properties"/>
</beans>

3 配置web.xml

<!-- 多環境配置 在上下文context-param中設定profile.default的預設值 -->
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>production</param-value>
</context-param>

<!-- 多環境配置 在上下文context-param中設定profile.active的預設值 -->
<!-- 設定active後default失效,web啟動時會載入對應的環境資訊 -->
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>test</param-value>
</context-param>

這樣啟動的時候就可以按照切換spring.profiles.active的屬性值來進行切換了

也有更便捷的方法,通過jvm啟動時設定屬性spring.profiles.active或者依賴於maven 的profile來打包,可自行百度

二 擴充套件專案中出現載入配置檔案情況

專案中可能會出現這樣的情況,比如配置一些上傳檔案的路徑 FTP的資訊 以及一些回撥介面;這類配置資訊不是向資料庫配置檔案 redis那樣在專案啟動時載入,而是在類裡通過ResourceBundle 或是ClassLoder載入 

1.寫個listener實現 ServletContextListener介面 

package cn.jeeweb.core.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @ClassName:myContextListener
 * @Description:獲取webxml配置的環境用於PropertiesUtil工具類中動態匯入.properties檔案
 * @Created by wenbin.li on 2018/10/18
 */
public class ProfileContextListener implements ServletContextListener {

    public static String profile;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        profile = sce.getServletContext().getInitParameter("spring.profiles.active");
        if (profile == null || profile.equals("")) {
            profile = sce.getServletContext().getInitParameter("spring.profiles.default");
        }
        profile = "config_" + profile + "/";
        //動態改變log4j的配置檔案
        //  String log4jConfigLocation = sce.getServletContext().getInitParameter("log4jConfigLocation");
        //  sce.getServletContext().setInitParameter("log4jConfigLocation", "classpath:"+profile + "log4j.properties");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

2.修改web.xml 

<!--多環境配置 監聽器-->
<listener>
    <listener-class>cn.jeeweb.core.listener.ProfileContextListener</listener-class>
</listener>

3.在載入配置檔案時判斷一下不是common下面的配置檔案 就直接通過listener裡的靜態變數profile拼接路徑獲取就行