spring 中读取properties 文件

本文介绍如何在Java中创建静态类来读取配置文件,并在页面中直接使用这些值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/yqweber/p/3999782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值