一般情况下,我们都会采用spring xml + propeties文件的形式对java代码中的某些属性进行配置。但在一些比较小的程序中,其实根本用不到
Spring框架,不需要依赖注入。此时,我们可以直接应用properties文件,具体配置方法如下:
注意:下面的pro.properties文件只需要被放在BuildPath下面即可。
public class ProConfig {
private static Logger logger = Logger.getLogger(ProConfig.class);private Properties properties = new Properties();
public static final ProConfig Default = new ProConfig("/pro.properties");
public ProConfig(String configPath) {
InputStream is = null;
try {
is = ProConfig.class.getResourceAsStream(configPath);
properties.load(is);
} catch (IOException e) {
logger.error("Failed to load config file at: " + configPath, e);
} finally {
if (is == null) {
return;
}
try {
is.close();
} catch (IOException e) {
logger.error(
"Failed to close input stream when loading config file at: "
+ configPath, e);
}
}
}
public Properties getProperties() {
return properties;
}
public String getProperty(String name) {
return properties.getProperty(name);
}
public int getInt(String name) {
return getInt(name, 0);
}
public int getInt(String name, int defVal) {
int ret = defVal;
try {
ret = Integer.parseInt(properties.getProperty(name));
} catch (Exception e) {
}
return ret;
}
public long getLong(String name) {
return getLong(name, 0L);
}
public long getLong(String name, long defVal) {
long ret = defVal;
try {
ret = Long.parseLong(properties.getProperty(name));
} catch (Exception e) {
}
return ret;
}
public boolean getBoolean(String name) {
return getBoolean(name, false);
}
public boolean getBoolean(String name, boolean defVal) {
boolean ret = defVal;
try {
ret = Boolean.parseBoolean(properties.getProperty(name));
} catch (Exception e) {
}
return ret;
}