配置文件不存在时properties.load()会抛ioexception,应捕获filenotfoundexception走默认值,其他ioexception需warn日志;getresourceasstream()返回null须判空;@value的默认值不适用于外部设为空串场景,推荐@configurationproperties配合字段初始化。

配置文件不存在时,Properties.load() 会直接抛 IOException
Java 原生读取 application.properties 或自定义配置文件时,很多人直接用 Properties.load(new FileInputStream("config.properties")),但只要文件路径不对、权限不足或磁盘不可读,就会炸出 IOException——这会导致整个应用启动失败,连降级逻辑都跑不到。
真正该做的是:把文件 I/O 操作包裹在 try-catch 里,并明确区分「文件缺失」和「格式错误」两类问题:
-
FileNotFoundException属于预期中的常见情况,应走默认值逻辑 -
IOException(非FileNotFoundException)可能是磁盘满、编码异常等严重问题,需记录 warn 日志但不中断流程 - 别 catch
Exception,否则会吞掉NullPointerException这类编程错误
try (InputStream is = getClass().getResourceAsStream("/config.properties")) {
if (is == null) {
// 资源未打包进 classpath,视为缺失,走默认值
props.put("timeout", "3000");
props.put("retries", "2");
return;
}
props.load(is);
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
log.warn("config.properties not found, using defaults");
} else {
log.warn("failed to load config.properties, using defaults", e);
}
}
Spring Boot 中 @Value 无法自动 fallback 到默认值?
写 @Value("${db.url:jdbc:h2:mem:test}") 看似有默认值,但前提是这个 key 没被其他配置源(如环境变量、命令行参数)显式设为空字符串或 null。一旦外部配置把 db.url 设成了空串,@Value 就会原样注入空串,不会触发冒号后的默认值。
更稳的方式是用 @ConfigurationProperties 配合 @DefaultValue(仅限 Spring Boot 2.2+),或者手动校验:
立即学习“Java免费学习笔记(深入)”;
- 避免在
@Value中依赖复杂 fallback,尤其涉及多层嵌套或表达式 - 如果必须用
@Value,建议搭配Objects.requireNonNullElse或三元判断再赋值 -
@ConfigurationProperties的绑定过程会在类型转换后才应用默认值,对空字符串、"null"字符串等更鲁棒
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String url = "jdbc:h2:mem:test"; // 直接初始化字段
private int timeout = 3000;
// getter/setter
}
从 classpath 加载资源时,getResourceAsStream() 返回 null 不报错但很致命
这是最隐蔽的坑:getClass().getResourceAsStream("/config.properties") 在文件不存在时**静默返回 null**,后续如果直接传给 Properties.load(),会触发 NullPointerException,堆栈里还看不出哪少了文件。
务必在使用前判空,且不要只依赖 IDE 的资源拷贝设置——Maven 构建时若没配 <resources></resources>,src/main/resources 下的文件根本不会进 target/classes。
- 检查构建产物(如
target/classes/config.properties)是否存在 - 用
Thread.currentThread().getContextClassLoader().getResource("")打印 classpath 根路径,确认资源位置是否在其中 - 开发期可加断言:
if (is == null) throw new IllegalStateException("config.properties missing from classpath");
YAML 配置比 Properties 更易出错,尤其缩进和空值
用 YamlPropertiesFactoryBean 或 Spring Boot 的 YAML 支持时,一个不小心的空格或制表符就能让整个配置解析失败,抛出 ConstructorException 或 ParserException,而且错误提示极不友好,定位困难。
真实项目中,除非业务强依赖 YAML 的嵌套结构(比如多环境 profile 分组),否则建议优先用 .properties——它没有缩进语义、无引号歧义、JDK 原生支持、IDE 校验成熟。
- YAML 文件必须用空格缩进,禁止 Tab;层级差一个空格就解析失败
-
null值写成~或空字符串,但 Spring 对两者的处理不一致 - 若坚持用 YAML,至少加 CI 步骤跑
snakeyamlCLI 验证语法:java -jar snakeyaml-cli.jar parse config.yml










