Spring Boot中@NotNull注解对应用配置属性不生效如何解决
Spring Boot 配置属性非空校验失效修复方案
第一步:引入校验依赖
Spring Boot 2.3及更高版本默认未集成校验组件,需手动引入spring-boot-starter-validation依赖,Maven配置如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
第二步:添加校验启用注解
在配置属性绑定类上添加@Validated注解开启校验能力,仅给字段加@NotNull不会自动触发校验。
修正后的完整代码示例
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; // Spring Boot 3.x 替换为 jakarta.validation.constraints.NotNull import javax.validation.constraints.NotNull; import java.net.URI; @Data @Validated @ConfigurationProperties("spring.security.oauth2.resourceserver") public class ABCProperties { @NotNull(message = "配置项 spring.security.oauth2.resourceserver.my-property 不能为空") private URI myProperty; }
可选适配配置
如果属性类未加@Configuration注解,需在项目启动类上添加@EnableConfigurationProperties(ABCProperties.class),或在全局配置类添加@ConfigurationPropertiesScan自动扫描所有配置属性类。
配置完成后,对应配置项为空或未配置时,项目启动阶段会直接抛出ConstraintViolationException异常终止启动,从根源避免运行时出现空指针问题。
内容的提问来源于stack exchange,提问作者emoleumassi
相关产品推荐
相关产品推荐

