PAYATHON 2026

如何在 Spring Boot 中交叉校验配置属性?

数据阿明

可以在 @ConfigurationProperties 类中使用 @Validated 和 @AssertTrue,校验 callLegacy || callNewApi。配置 Bean 在启动期间创建并绑定时,校验会拒绝两个开关同时为 false 的配置,避免等到业务方法执行时才发现问题。

校验规则是“至少开启一个”

使用逻辑或 ||,可以允许两个服务同时开启:

callLegacy callNewApi 是否允许
true false 允许
false true 允许
true true 允许
false false 拒绝

不要分别给两个字段添加 @AssertTrue,否则两个开关都必须为 true。

配置绑定和校验代码

下面的示例使用 Spring Boot 3.x 的 jakarta.validation 命名空间。如果项目使用 javax.validation,请根据项目依赖调整 import。

先确保项目包含 Bean Validation 实现。使用 Spring Boot 依赖管理的 Maven 项目可以添加:

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

定义配置类:

import jakarta.validation.constraints.AssertTrue;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

@ConfigurationProperties(prefix = "employee-engine")
@Validated
public class EmployeeEngineProperties {

    private boolean callLegacy = true;
    private boolean callNewApi = true;

    public boolean isCallLegacy() {
        return callLegacy;
    }

    public void setCallLegacy(boolean callLegacy) {
        this.callLegacy = callLegacy;
    }

    public boolean isCallNewApi() {
        return callNewApi;
    }

    public void setCallNewApi(boolean callNewApi) {
        this.callNewApi = callNewApi;
    }

    @AssertTrue(message =
        "employee-engine.call-legacy 和 employee-engine.call-new-api 不能同时为 false")
    public boolean isAtLeastOneEnabled() {
        return callLegacy || callNewApi;
    }
}

@AssertTrue 要求被校验的布尔值为 true,具体语义可参见 Jakarta Validation 文档。

isAtLeastOneEnabled() 是一个公开、无参数、返回 boolean 的 JavaBeans getter,可以参与对象属性校验。不要把它改成 checkConfiguration(),然后假定普通对象校验仍会执行该方法。Bean Validation 规范规定了 getter 的识别方式。

在应用入口注册配置类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(EmployeeEngineProperties.class)
public class Application {

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

如果项目已经通过 @ConfigurationPropertiesScan 扫描到这个类,就不必重复注册。

配置文件建议统一使用 kebab-case:

employee-engine.call-legacy=true
employee-engine.call-new-api=true

@ConfigurationProperties 的 prefix 应使用 kebab-case;.properties 中原有的 camelCase 写法可以通过宽松绑定匹配。配置 Bean 上的 @Validated 配合类路径中的校验实现启用校验,参见 Spring Boot 配置文档。

示例将两个字段初始化为 true,与原代码希望表达的默认值一致。如果希望两个属性都未配置时也报错,可以去掉初始化,让两个基本类型字段默认均为 false。

如何读取属性值并记录日志

业务服务可以通过构造器注入配置对象,再调用 getter 读取属性值:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class BusinessService {

    private static final Logger LOGGER =
        LoggerFactory.getLogger(BusinessService.class);

    private final EmployeeEngineProperties properties;

    public BusinessService(EmployeeEngineProperties properties) {
        this.properties = properties;
    }

    public void logConfiguration() {
        LOGGER.info("callLegacy={}, callNewApi={}",
            properties.isCallLegacy(),
            properties.isCallNewApi());
    }
}

读取到的是绑定后的值,包括代码中的默认值。两个开关同时为 false 时,正常启动流程会在配置校验阶段失败,因此不应依靠后续业务方法记录这次失败。

原示例中的 @Value 还缺少 ${...}。如果继续使用字段注入,正确写法是:

@Value("${employee-engine.call-legacy:true}")
private boolean callLegacy;

@Value("${employee-engine.call-new-api:true}")
private boolean callNewApi;

异常消息里如何显示实际值

普通 Java 异常消息需要显式拼接或格式化字段值。字符串中的 {callLegacy}、{callNewApi} 不会自动替换为变量值。

Bean Validation 的 message 也不能通过这些占位符直接读取同名字段。对于当前规则,校验失败时两个字段必然都是 false,因此示例中的固定消息可以准确说明错误。

如果以后要校验更多字段,并在错误消息中动态输出它们的值,可以定义类级约束,在 ConstraintValidator 中读取整个 EmployeeEngineProperties 对象,再通过 ConstraintValidatorContext 构造错误消息。当前只有一条布尔组合规则,使用 getter 上的 @AssertTrue 即可。

备注:内容仅供参考。