1. 程式人生 > >spring profile啟用處理

spring profile啟用處理

1.使用背景

專案開發一共有三個環境:測試環境,灰度環境和生產環境,比如我們想在測試環境下,不載入某些配置資訊,可以通過profile來實現

2.啟用profile實現方式

  1. JVM增加引數spring.profiles.active設定
  2. 在ServletContextListener 中初始化屬性spring.profiles.active

3. JVM增加引數spring.profiles.active設定

在JVM中增加引數spring.profiles.active設定,如果我們想設定spring.profiles.active為dev,使用Dspring.profiles.active=”dev” 。

此種方式需要修改tomcat的JVM配置,通用性不高。

4. 在ServletContextListener 中初始化spring.profiles.active

寫一個類InitConfigListener實現介面ServletContextListener,重寫容器初始化方法contextInitialized(),設定屬性為spring.profiles.active為指定值environment。
environment可以定義在一個屬性檔案中,在使用maven構建時使用測試,灰度或者生產環境的屬性檔案。
在contextInitialized方法中讀取指定屬性檔案,獲取environment 值,通過setProperty即可實現。

@WebListener
public class InitConfigListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String environment = "";
        //載入Properties屬性檔案獲取environment值 
        //偵測jvm環境,並快取到全域性變數中
        String env = System.setProperty("spring.profiles.active"
,environment); } @Override public void contextDestroyed(ServletContextEvent sce) { } }

spring.xml配置只在dev模式下載入配置檔案spring-mybatis.xml

<beans profile="dev">
    <import resource="spring-mybatis.xml" /> 
</beans>

springboot使用註解@Profile和@Configuration來配置,@ActiveProfiles()在測試時切換環境

大家可以關注我的公眾號:不知風在何處,相互溝通,共同進步。