您的位置:首页 > 编程语言 > Java开发

spring 中读取properties 文件

2014-09-29 11:08 274 查看
在src 目录下建立configs.properties

backup.host = 192.168.1.6
backup.user = root
backup.pwd =pwd


建立静态类:

package com.ly.jxc.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* 配置文件读取类
* @author yq
* 2014-09-29
*/
public class Configs extends PropertyPlaceholderConfigurer {

private static Map<String, Object> ctxPropertiesMap;

protected static void load(){
Resource resource = new ClassPathResource("/config.properties");
Properties props;
try {
props = PropertiesLoaderUtils.loadProperties(resource);

ctxPropertiesMap = new HashMap<String, Object>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
ctxPropertiesMap.put(keyStr, value);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 返回int,带默认值
* @param name
* @return
*/
public static int getIntValue(String name,int defaultValue) {
if(ctxPropertiesMap ==null ||ctxPropertiesMap.isEmpty())
load();
if(ctxPropertiesMap.get(name)==null)
return defaultValue;
return Integer.parseInt((String)ctxPropertiesMap.get(name));
}
/**
* 返回int
* @param name
* @return
*/
public static int getIntValue(String name) {
if(ctxPropertiesMap ==null ||ctxPropertiesMap.isEmpty())
load();
if(ctxPropertiesMap.get(name)==null)
return 0;
return Integer.parseInt((String)ctxPropertiesMap.get(name));
}

/**
* 返回string
* @param name
* @return
*/
public static String getValue(String name) {
if(ctxPropertiesMap ==null || ctxPropertiesMap.isEmpty())
load();
return (String)ctxPropertiesMap.get(name);
}
}


然后配置静态类(详见我另一篇 http://www.cnblogs.com/yqweber/p/3992513.html) 就能在页面直接用来取值了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: