上代码:
第一种方法:项目中引入org.apache.commons包。
方法调用: ConfigManager.getInstance.getConfig("");
public class ConfigManager {
public static final ConfigManager
configManager =
new ConfigManager();
private static Configuration
config;
private
ConfigManager() {
try
{
config =
new PropertiesConfiguration("config/config.properties");
}
catch (ConfigurationException e) {
e.printStackTrace();
}
}
public static ConfigManager getInstance() {
return
configManager;
}
public
String getConfig(String key) {
return
(String) config.getProperty(key);
}
public
Configuration getConfig() {
return
config;
}
第二种方法:引入spring-beans包。
方法调用:CustomerPropertyPlaceholder.getProperty("");
public class CustomerPropertyPlaceholder
extends PropertyPlaceholderConfigurer {
private static Map<String, String>
propertyMap;
@Override
protected void processProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props) throws
BeansException {
super.processProperties(beanFactoryToProcess, props);
propertyMap
= new HashMap<String, String>();
for
(Object key :
props.keySet()) {
String keyStr
= key.toString();
String value
= props.getProperty(keyStr);
propertyMap.put(keyStr,
value);
}
}
public static Object getProperty(String
name) {
return
propertyMap.get(name);
}
}
本文介绍了在Java中读取.properties配置文件的两种常见方法:一种是使用Apache Commons Configuration库,另一种是利用Spring的PropertyPlaceholderConfigurer。通过示例代码详细展示了如何实现从配置文件中获取属性值。
1万+

被折叠的 条评论
为什么被折叠?



