You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring项目如何读取Maven依赖包内的YAML配置文件?

读取Maven依赖中yml文件的解决方案

原有方案失效原因

  • 第一种方案使用的ResourceBundle仅支持读取.properties格式的资源束,原生不支持yml格式,无法直接使用
  • 第二种方案的路径配置存在问题:classpath:前缀仅会扫描当前项目的类路径资源,不会包含第三方依赖Jar包内的资源,因此无法匹配到依赖中的yml文件

正确实现方式

方案1:扫描所有类路径下的匹配资源

将资源路径前缀修改为classpath*:,该前缀会加载所有依赖Jar包内匹配路径的资源,代码示例如下:

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;

// 业务逻辑内代码
final ClassLoader classLoader = this.getClass().getClassLoader();
final ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);
Resource[] resources = new Resource[0];
try {
    // 使用classpath*:前缀扫描所有依赖中的资源
    resources = resolver.getResources("classpath*:**/rest/*.yml");
    for (Resource resource : resources) {
        if ("api-rest.yml".equals(resource.getFilename())) {
            // 读取并解析yml内容
            try (InputStream inputStream = resource.getInputStream()) {
                Yaml yaml = new Yaml();
                Map<String, Object> ymlContent = yaml.load(inputStream);
                // 此处处理解析后的yml内容
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

如果你的项目没有引入snakeyaml依赖,需要在pom.xml中添加:

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>2.2</version>
</dependency>

Spring Boot项目默认已经集成该依赖,无需额外引入。

方案2:已知文件完整路径直接加载

如果你明确api-rest.yml在依赖Jar中的完整路径,比如直接存放在类路径根目录,可以直接加载单个资源:

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;

// 注入资源加载器
@Autowired
private ResourceLoader resourceLoader;

public void loadApiRestYml() throws Exception {
    Resource resource = resourceLoader.getResource("classpath*:api-rest.yml");
    try (InputStream inputStream = resource.getInputStream()) {
        // 解析逻辑同方案1
    }
}

前置校验

如果修改后还是无法读取,先排查依赖Jar的打包配置:

  • 解压对应的Maven依赖Jar,确认api-rest.yml确实存在于类路径目录下(而非META-INF等非类路径目录)
  • 如果该依赖是你自行维护的,确认其pom.xml的resources配置没有排除.yml后缀的文件。

内容的提问来源于stack exchange,提问作者Luis Gustavo Oliveira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:36:02