首页 归档 关于 learn love 工具

spring 解析 yaml 配置文件

properties 和 yml 区别

properties 和 yml 都是 Spring Boot 支持的两种配置文件,它们可以看作是 Spring Boot 在不同时期的两款“产品”。在 Spring Boot 时代已经不需要使用 XML 文件格式来配置项目了,取而代之的是 properties 或 yml 文件。

properties 配置文件属于早期,也是目前创建 Spring Boot(2.x)项目时默认的配置文件格式,而 yml 可以看做是对 properties 配置文件的升级,属于 Spring Boot 的“新版”配置文件。

properties 翻译成中文是“属性”的意思,所以它在创建之初,就是用来在 Spring Boot 中设置属性的。
yml 是 YAML 是缩写,它的全称 Yet Another Markup Language,翻译成中文是“另一种标记语言”。

所以从二者的定义可以看出:它们的定位和层次是完全不同的,properties 只是用来设置一些属性配置的,而 yml 的格局和愿景更大,它的定位是“另一种标记语言”,所以从格局上来讲 yml 就甩 properties 好几条街。

Properties 解析

参考 mybatis 测试用例 ,链接

Properties props = Resources.getResourceAsProperties("org/apache/ibatis/databases/blog/blog-derby.properties");
System.out.println(props.getProperty("driver")); 

yml 解析

在 Spring Framework 中,解析 YAML 文件通常使用 YamlPropertiesFactoryBean 工具类。这个工具类允许您将 YAML 文件中的配置属性解析为 Spring 的 Properties 对象,以便在应用程序中使用。

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

public class YamlParser {

    public static Properties parseYamlFile(String yamlFilePath) {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(new ClassPathResource(yamlFilePath)); // 指定 YAML 文件路径
        return factory.getObject();
    }

    public static void main(String[] args) {
        Properties properties = parseYamlFile("application.yml"); // 传入 YAML 文件名
        if (properties != null) {
            System.out.println("Parsed properties from YAML file:");
            properties.forEach((key, value) -> System.out.println(key + " = " + value));
        } else {
            System.out.println("Failed to parse YAML file.");
        }
    }
}