spring 中读取properties 文件

在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) 就能在页面直接用来取值了.

你可能感兴趣的:(properties)