获取Yaml文件中的数据

1、新建一个注解,方便查看方法读取的yaml的具体内容

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestCaseFlorder {

   String casePath() default "";
}

2、在resource目录下新建一个yaml文件,文件中输入数据

caseName: case001
description: desc001
dataItem:
  a: 34
  b: 58

---
#多个用例数据用"---"分开

caseName: case002
description: desc002
dataItem:
  a: 23
  b: 89


3、测试方法

    @Test
    @TestCaseFlorder(casePath = "/testPath/data.yaml" )
    public void getYamldata() throws Exception {
        String path = "src/main/resources";
        TestCaseFlorder testCaseFlorder = YamlFileTest.class.getMethod("getYamldata").getAnnotation(TestCaseFlorder.class);
        File  file = new File(path+testCaseFlorder.casePath());
        FileInputStream fileInputStream = new FileInputStream(file);
        Yaml yaml = new Yaml();
        Iterable<Object> objects = yaml.loadAll(fileInputStream);
        for (Object yamldata: objects) {
            System.out.println(yamldata);
        }
    }
}

结果:
在这里插入图片描述

在 Spring Boot 应用中,当尝试通过 YAML 文件配置 ShardingSphere 数据源时,若未能正确加载配置文件或路径错误,可能会抛出 `NullPointerException`。为避免此类问题,需要确保资源路径的准确性,并在读取前进行空值校验。 ### 正确加载 YAML 配置文件的方法 在 Spring Boot 中加载 YAML 文件通常使用 `ClassLoader.getResource()` 方法获取资源 URL。例如: ```java URL yamlFileUrl = getClass().getClassLoader().getResource("sharding-config.yaml"); ``` 如果返回值为 `null`,说明该文件未被正确识别或未包含在类路径中。此时应抛出异常以提示开发者检查配置文件是否存在[^1]: ```java if (yamlFileUrl == null) { throw new IllegalArgumentException("Sharding configuration file not found in classpath."); } ``` ### 确保 YAML 文件位于类路径中 YAML 配置文件应放置在 `src/main/resources` 目录下,以便在构建过程中自动打包进应用。例如,若配置文件名为 `sharding-config.yaml`,则其完整路径应为 `src/main/resources/sharding-config.yaml`。构建完成后,可通过解压 JAR 包确认该文件是否存在于 `BOOT-INF/classes/` 路径下。 ### 使用 SnakeYAML 依赖解析 YAML 文件 为确保能够成功解析 YAML 文件内容,需在 `pom.xml` 中引入 `snakeyaml` 依赖[^2]: ```xml <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.20</version> </dependency> ``` 随后可使用如下代码读取并解析 YAML 内容: ```java Yaml yaml = new Yaml(new Constructor(YamlRootConfiguration.class)); YamlRootConfiguration config = yaml.load(new FileInputStream(yamlFileUrl.getFile())); ``` ### 添加日志输出以辅助调试 在数据源初始化过程中添加日志输出,有助于快速定位问题根源。例如: ```java try { YamlRootConfiguration config = new YamlRootConfiguration(yamlFileUrl); // 构建数据源逻辑 } catch (IOException e) { logger.error("Failed to load sharding configuration", e); throw new RuntimeException(e); } ``` ### 示例:完整的 ShardingDataSource 初始化方法 以下是一个完整的 `shardingDataSource` 方法示例,包含路径校验、日志输出及异常处理: ```java @Bean public DataSource shardingDataSource() throws IOException { URL yamlFileUrl = getClass().getClassLoader().getResource("sharding-config.yaml"); if (yamlFileUrl == null) { throw new IllegalArgumentException("Sharding configuration file not found in classpath."); } try { Yaml yaml = new Yaml(new Constructor(YamlRootConfiguration.class)); YamlRootConfiguration config = yaml.load(new FileInputStream(yamlFileUrl.getFile())); return ShardingSphereDataSourceFactory.createDataSource(config); } catch (IOException e) { logger.error("Failed to load sharding configuration", e); throw e; } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值