spring中如何读取.properties配置文件

主要使用了spring-core-4.1.4.RELEASE-sources.jar 这个jar包里的 PropertiesLoaderUtils.loadProperties 方法。不说了,直接上代码:

package cn.lyj.util;

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

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ExcutePro {
	
	//读取.properties 结尾的配置文件用,getP, getParam
	public static Map<String,String> getP(String path) throws Exception{
		Resource resource = new ClassPathResource(path);
		Properties props = PropertiesLoaderUtils.loadProperties(resource);
		Map<String,String> param = new HashMap<String,String>((Map) props);
		return param;
	}
	
}

其中 Properties props ,java.util.Properties是对properties这类配置文件的映射,支持key-value类型和xml类型两种。

properties类实现了Map接口,所以很明显,他是用map来存储key-value数据,所以也注定存入数据是无序的,这个点需要注意。

针对key-value这种配置文件,是用load方法就能直接映射成map,非常简单好用。


如何使用:
Map<String, String> app = ExcutePro.getP("app.properties");
String ftpUrl = app.get("ftp.server.url");//Map类型,通过get("key")来得到结果

这样我们就能得到 app.properties 文件里的 ftp.server.url  的值


附 app.properties文件的代码
#ftp configure info
ftp.username = admin
ftp.password = 123456
ftp.server.url = 172.16.251.95
ftp.port = 21


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值