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

如何为外部库中的类加载@ConfigurationProperties并填充属性?

我之前碰到过一模一样的问题,在Spring Boot 1.5.x版本里用第三方库的类做@ConfigurationProperties Bean时,确实会踩这个验证时机的坑——Spring会在属性绑定完成前就执行JSR-380验证,这时候字段还是默认的null值,自然就抛出验证异常了。

问题根源

你的CommonPerson类已经加了@Validated和字段级的@NotNull,但因为它属于外部公共库,Spring Boot 1.5.x的默认逻辑不会自动调整验证时机,而是在Bean实例化后立刻触发验证,完全没等到配置属性绑定上去。

解决方案

1. 在@Bean方法上添加@Valid注解

修改你的MainApp里的Bean定义方法,加上@Valid注解,强制Spring在属性绑定完成后再执行验证:

package com.my.api;

import com.my.commons.person.CommonPerson;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import javax.validation.Valid;

@SpringBootApplication
public class MainApp extends SpringBootServletInitializer {

    @Bean
    @ConfigurationProperties("commons.person")
    @Valid // 关键:添加此注解,确保绑定后再验证
    public CommonPerson person() {
        return new CommonPerson();
    }

    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

2. 确认引入验证依赖

虽然你把类移到本地项目能正常运行,但还是要检查下Maven是否引入了Spring Boot的validation starter(1.5.x版本需要单独引入):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

为什么移到本地项目就正常?

当CommonPerson在你的项目包下时,Spring Boot的组件扫描会自动识别类上的@Validated,并自动调整验证时机;但对于第三方库的类,这种自动处理逻辑不生效,必须通过@Valid注解明确指定验证时机。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:50:53