一般项目中都有读取配置信息的基本要求。下面记录一些实用的方法。
1. 使用工具类propertiesUtil
package com.lingnanpass.common.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* Properties属性集合,读取项目根路径下的config.properties文件
* 创建时间:2016年11月17日 下午2:45:06
*/
public class PropertiesUtil {
private static Logger logger = LogManager.getLogger(PropertiesUtil.class);
//属性文件的路径
static String profile="config.properties";
private static Properties props = new Properties();
static {
try {
props.load(PropertiesUtil.class.getResourceAsStream("/"+profile));
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(profile+" is not found:"+e.getMessage());
} catch (IOException e) {
logger.error(profile+" I/O exception:"+e.getMessage());
}
}
/**
* 获取prop的制定key的值
* @param key
* @return
*/
public static String get(String key) {
return props.getProperty(key);
}
/**
* 插入一对prop
* @param key
* @param name
*/
public static void set(String key,String value) {
props.setProperty(key, value);
}
}
2. 通过注解@Value读取配置
第一步:
首先spring的applicationContext.xml文件引入配置文件
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"></property>
</bean>
第二步:
配置jdbc.properties文件
jdbc.initialPoolSize =2
jdbc.maxWaitTime =60000
jdbc.checkIdlePoolTime = 60000
jdbc.minConnTime = 300000
name=nihao
第三步:
通过注解@Value获取配置信息
@Value("#{configProperties['name']}")
private String name;