配置参数校验应在配置类初始化后、服务启动前完成,推荐使用@PostConstruct或@Validated配合@ConfigurationProperties;校验失败需明确反馈具体字段和规则,避免堆栈深、定位难。
校验逻辑不能等到业务方法里才触发,否则异常堆栈深、定位成本高。推荐在配置类初始化后、服务启动前完成校验,即 @PostConstruct 或 InitializingBean.afterPropertiesSet() 中执行;Spring Boot 2.3+ 更建议用 @Validated 配合 @ConfigurationProperties 原生支持。
@ConfigurationProperties 时,必须显式加 @Validated 才会触发 JSR-303 校验@Valid 不生效——它只对 Spring 管理的 Bean 生效BindException(非运行时异常),需配 @Control
lerAdvice 统一捕获,或改用 Validated 让其抛 MethodArgumentNotValidException
@NotNull 和 @NotBlank 容易混用:@NotNull 只防 null,不防空字符串或纯空格;@NotBlank 会 trim 后判长度,但仅适用于 String 类型。数值类字段常用 @Min(1),但注意 int 默认初值为 0,若未显式赋值且未设 @Null,校验可能被跳过。
@Pattern(regexp = "^\\d{11}$") 要注意正则边界,漏写 ^ 和 $ 会导致部分匹配通过ConstraintValidator,且验证器类要被 Spring 扫描到(不能是 static 内部类)@Email 校验宽松,仅检查是否含 @ 和域名格式,不验证真实可达性Spring Boot 默认将 BindException 渲染成 HTTP 500,这对配置加载阶段极不友好。应在启动时就阻断,而不是等接口调用才暴露问题。可通过 ApplicationContextInitializer 提前触发校验,或监听 ApplicationPreparedEvent。
@ConfigurationProperties 类中添加 validate() 方法,并在 @PostConstruct 中调用,手动抛 IllegalArgumentException
@Value 注入场景下做校验——它不支持任何注解校验,只能靠后续代码判断BindingResult.getAllErrors() 提取明细
@ConfigurationProperties(prefix = "app.db")
@Validated
public class DatabaseProperties {
@NotBlank(message = "url must not be blank")
private String url;
@Min(value = 1, message = "port must be >= 1")
private int port = 3306;
@PostConstruct
public void validate() {
if (url != null && !url.startsWith("jdbc:")) {
throw new IllegalArgumentException("app.db.url must start with 'jdbc:'");
}
}
// getter/setter...
}
当配置含 List 或 Map 时,仅在字段上加 @Valid 不够——必须在集合元素类型上也标注 @Valid,否则子对象内部注解不生效。
List 是合法写法(Java 8+ type annotation),但部分 IDE 可能报黄线,实际运行有效Map 的 key 不校验,value 需用 @Valid 标在字段上,如 @Valid private Map pools;
@PostConstruct,注意 Spring 初始化顺序:父类 @PostConstruct 先于子类字段注入完成,此时子对象可能还是 null