> ## Documentation Index
> Fetch the complete documentation index at: https://blog.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Spring Boot 3.4 配置属性的 Bean Validation 新特性

## Bean Validation 规范是什么？

**Jakarta Bean Validation 规范**（前身是 **JSR 380**、**349** 和 **303**）解决了一个标准化的需求：允许开发者通过注解方式在对象模型上表达**约束**，并提供用于验证对象、方法参数和构造函数返回值的 API。

以下示例代码使用 JSR 380 注解（如 `@NotNull` 和 `@Email`）来验证 `Customer` 类：

```java theme={null}
public class Customer {
    @NotNull
    private String name;
    
    @Email
    private String email;
    
    @Pattern(regexp = "^1[3-9]\\d{9}$")
    private String mobile;
    
    // getters and setters
}
```

## Spring Boot 如何使用 Bean Validation？

Spring Boot 通过多种方式集成了 Bean Validation：

### 使用 @Validated 和 @Valid

在 Spring Boot 中，我们可以使用 `@Validated` 和 `@Valid` 注解来触发验证：

1. `@Validated` 用于类级别，启用验证功能
2. `@Valid` 用于字段或方法参数级别，表示需要验证的嵌套对象

```java theme={null}
@Validated
@Service
public class CustomerService {
    public void registerCustomer(@Valid Customer customer) {
        // 处理客户注册逻辑
    }
}
```

## 配置属性的 Bean Validation

Spring Boot 允许我们对配置属性类进行验证。这些类通常使用 `@ConfigurationProperties` 注解标记。

### Spring Boot 3.4 之前的行为

在 Spring Boot 3.4 之前，配置属性的验证行为如下：

1. 主配置类上的 `@Validated` 注解会触发所有配置属性的验证
2. 嵌套属性的验证需要在字段上使用 `@Valid` 注解

```java theme={null}
@Validated
@ConfigurationProperties("mall")
public class MallProperties {
    @Valid
    private PaymentConfig payment;
    
    public static class PaymentConfig {
        @NotNull
        private String provider;
        // getters and setters
    }
}
```

### Spring Boot 3.4 的新行为

Spring Boot 3.4 改变了验证行为：

1. 配置属性类上的 `@Validated` 注解现在会自动触发所有嵌套属性的验证
2. 不再需要在嵌套属性字段上显式添加 `@Valid` 注解

```java theme={null}
@Validated
@ConfigurationProperties("mall")
public class MallProperties {
    // 不再需要 @Valid
    private PaymentConfig payment;
    
    public static class PaymentConfig {
        @NotNull
        private String provider;
        // getters and setters
    }
}
```

### 总结

1. 在 Spring Boot 3.4 中，我们不需要在 `AppProperties` 的 `security` 字段上添加 `@Valid` 注解，嵌套验证会自动进行。

2. 配置属性类使用 `@Validated` 注解就足够了，它会自动处理所有嵌套属性的验证。

3. 使用 `@ConfigurationPropertiesScan` 可以自动扫描和注册所有的 `@ConfigurationProperties` 类。

4. 验证注解（如 `@NotBlank`、`@Min`、`@Max` 等）可以直接应用在嵌套类的字段上。

Spring Boot 3.4 对配置属性的 Bean Validation 进行了简化，使得验证更加直观和易用。这个改变虽小，但提升了开发体验，减少了样板代码。然而，由于这是一个破坏性变更，在升级时需要特别注意。
