1. 程式人生 > >Spring 根據maven所選的Profies載入不同的配置檔案,免切換測試生產配置檔案。

Spring 根據maven所選的Profies載入不同的配置檔案,免切換測試生產配置檔案。

 直接貼程式碼吧,以後再加註釋


package com.jmev.web.util.config;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author qiwenshuai
 * @description
 * @since 18-7-13 14:15 by jdk 1.8
 */
public class Config {


    private  
String type; private static Properties prop = null; @PostConstruct public void setProperties() throws IOException { prop = new Properties(); prop.load(new InputStreamReader(ConfigUtils.class.getClassLoader().getResourceAsStream(type),"UTF-8")); } public String getType
() { return type; } public void setType(String type) { this.type = type; } public Properties getMap(){ return prop; } }
package com.jmev.web.util.config;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStreamReader; import java.util.Properties; /** * @author qiwenshuai * @description * @since 18-7-13 14:57 by jdk 1.8 */ public class ConfigUtils { @Resource private Config Config; private static Properties properties = new Properties(); @PostConstruct public void map() { properties = Config.getMap(); } public static String getPropValues(String key) { if ((properties == null || properties.size() == 0)) { setProperty(); } return properties.getProperty(key); } private static void setProperty() { try { //保證安全情況下載入生產環境下的檔案 properties.load(new InputStreamReader(ConfigUtils.class.getClassLoader().getResourceAsStream("product/productConfig.properties"), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } } }

application.xml

<bean id ="Config" class="com.jmev.web.util.config.Config">
   <property name="type"  value="${config.environment}"></property>
</bean>

<bean id ="MyConfig" class="com.jmev.web.util.config.ConfigUtils"></bean>

部分pom,在<profile><id>local</id></profile> <properties中進行配置自定義屬性>

<config.environment>local/localConfig.properties</config.environment>

在<profile><id>product</id></profile> <properties中進行配置自定義屬性>

<config.environment>product/productConfig.properties</config.environment>

resources目錄下 分別加

local/localConfig.properties
product/productConfig.properties

就OK,裡面分別是本地和生產。