Java Properties 读取xml 文件做字典数据

java哥 阅读:685 2021-03-31 12:54:45 评论:0

情况:今天上班时遇到一个头疼的情况,数据迁移工具中的数据字典类实例化失败(通过springframework 框架的ApplicationContext 全局上下文获取 字典服务连接数据库查询相关数据信息),我们先把这种方式归类为spring 动态注入方式,

由于项目紧急,没有多余的时间允许我去排查问题是如何产生的,我临时涉及一种替代spring动态注入方式,设计思路(定义一个数据字典对象类,在调用构造函数时向数据字典对象类的Map属性注入字典值,字典值的存储方式分为:*.properties 和*.xml 方式)

字典值的存储方式建议采用xml 方式存储,*.properties 存储存在字符乱码问题。本文也是基于:xml文件方式存储。

核心功能代码:通过Properties 对象加载指定xml 文件,并将xml 文件内容赋值给Map 对象。

public class DataDictFieldProcess implements  FieldProcess { 
	// 日志记录 
	public static final Logger log = LoggerFactory.getLogger(DataDictFieldProcess.class); 
	private static final String FILE_NAME = "dict.cfg.xml"; 
	 
	Map<String, String> dataDictMap = null; 
	 
	public DataDictFieldProcess() { 
		super(); 
		InputStream input = DataDictFieldProcess.class.getClassLoader().getResourceAsStream(FILE_NAME); 
		if(input != null){ 
			try { 
				if(dataDictMap == null){ 
					dataDictMap = new HashMap<String,String>(); 
				} 
				Properties properties = new Properties(); 
				properties.loadFromXML(input); 
				 
				properties.keySet().stream().forEach(item ->{ 
					String key = String.valueOf(item); 
					dataDictMap.put(key, properties.getProperty(key, "")); 
				}); 
				 
				 
			}catch (Exception e) { 
				log.error("Load column.cfg.xml error", e); 
			}finally { 
                if (input != null) { 
                    try { 
                    	input.close(); 
                    	input = null; 
                    } catch (IOException e) { 
                    	log.error("InputStream Colse Error:", e); 
                    } 
                } 
            } 
		} 
		 
	}

 

标签:XML
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号