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

来源:互联网 发布:node.js 安装教程 编辑:程序博客网 时间:2024/06/05 09:08

主要使用了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, getParampublic 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 infoftp.username = adminftp.password = 123456ftp.server.url = 172.16.251.95ftp.port = 21


1 0