从spring、spring boot中找到解析properties、xml、yml、yaml文件的方法

一、解析properties和xml

  • 这里使用了FileSystemResource,spring的Resource继承于InputStreamSource,也就是spring封装了InputStreamSource;可以从spring源码看到除了FileSystemResource还有其他的实现,比如可以不用绝对路径用ClassPath,对应的实现类就是ClassPathResource
    在这里插入图片描述
/***
	 * 解析Properties 、xml
	 * */
	public static void loadProperties(){

		// 第一种
		Properties props = new Properties();
		//查找配置文件的属性 并且都合并到props
		FileSystemResource location = new FileSystemResource(new File("F:\\work\\unknown\\unknown-admin\\config\\application.properties"));
		try {
			PropertiesLoaderUtils.fillProperties(props, new EncodedResource(location, (String) null));
			System.out.println(props.getProperty("zookeeper.address"));
		} catch (IOException e) {
			e.printStackTrace();
		}

		//第二种 spring boot的
		try {
			List<PropertySource<?>>  propertySourceList = new PropertiesPropertySourceLoader().load("app",new FileSystemResource("F:\\work\\unknown\\unknown-admin\\config\\application.properties"));
			System.out.println(propertySourceList.get(0).getProperty("zookeeper.address"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

二、解析yml和yaml

  • 这里我就使用的ClassPathResource实现,根据自己实际情况选择用哪个具体实现。
	/***
	 * 目前从源码中找到的读取yml、yaml文件的两种方式
	 * */
	public static void loadYml(){
		// 第一种  spring boot解析yml
		YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		//yaml.setResources(new FileSystemResource("config.yml"));//File引入
		yaml.setResources(new ClassPathResource("/application-dev.yml"));//classPath引入
		System.out.println(yaml.getObject().get("spring.data.mongodb.uri"));



		//第二种  YamlPropertySourceLoader
		Resource resource = new ClassPathResource("/application-dev.yml");
		//List<Map<String, Object>> loaded = new OriginTrackedYamlLoader(resource).load();
		try {
			List<PropertySource<?>>  propertySourceList = new YamlPropertySourceLoader().load("/application.yml",resource);
			System.out.println(propertySourceList.get(0).getProperty("spring.data.mongodb.uri"));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

三、总结和运行效果

  • 用spring源码里解析配置文件的方法还是挺方便的,一、两行代码就搞定了,也不用去关流之类的,spring里面已经做了。
  • 下面看下总体运行效果
    在这里插入图片描述
  • 本篇到此结束,我再捋一捋后续有时间会出解析配置文件的源码分析,感谢您的观看,如果文章有问题,希望您能指正。
  • spring读取配置文件原理解析已经写了,欢迎大家观看和提意见- 2020年6月22日11:08:11

posted on   愤怒的苹果ext  阅读(216)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示