直接贴代码吧,以后再加注释
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,里面分别是本地和生产。