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

配置ignoreResourceNotFound=true仍抛出FileNotFoundException问题咨询

问题原因

ignoreResourceNotFound = true 属性本身是生效的,但你的自定义 YamlPropertySourceFactory 没有适配这个逻辑——当资源不存在时,你依然强行尝试加载资源并转换为Properties,直接触发了文件不存在的异常,导致Spring上下文初始化失败。

Spring原生的PropertySourceFactory实现会在ignoreResourceNotFound=true时跳过不存在的资源加载,但自定义实现需要自行处理这个判断逻辑。

修复方案

修改YamlPropertySourceFactory的代码,先检查资源是否存在,不存在则返回null(Spring会自动忽略null的PropertySource),避免强行加载不存在的文件:

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
        Resource resource = encodedResource.getResource();
        // 先判断资源是否存在,不存在直接返回null
        if (!resource.exists()) {
            return null;
        }

        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource);

        Properties properties = factory.getObject();
        // 处理yaml文件存在但内容为空的情况,避免NPE
        if (properties == null) {
            return new PropertiesPropertySource(resource.getFilename(), new Properties());
        }

        return new PropertiesPropertySource(resource.getFilename(), properties);
    }
}
额外说明
  1. 返回null时,Spring会结合ignoreResourceNotFound=true的配置,直接跳过该资源的注入逻辑,不会抛出异常。
  2. 增加properties == null的判断,是为了处理yaml文件存在但内容为空的场景,避免出现空指针异常。

内容的提问来源于stack exchange,提问作者karczi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:37:17