Spring Bean 验证 – JSR-303 注释

在本文中,我们将探讨如何将 JSR-303 注释应用于域对象的实际示例(从基本注释到高级注释) 。因此,基本上,注释提供了一种声明性方式来配置 Spring bean、管理依赖项和定义行为,从而减少对样板代码的需求,并使代码更加简洁和富有表现力。

什么是 Bean 验证?
Spring Boot 中的 Bean 验证 是确保输入应用程序的数据有效并满足您的特定要求的最重要工具。它基于 JSR-303 Bean 验证 规范,该规范标准化了 Java 中 Bean 的验证方式。 Spring Boot 中 bean 验证的主要用例是允许为 Java 对象定义数据完整性规则。这可确保对象在使用前满足要求。

使用 Spring Bean 验证和 JSR-303 注释进行数据验证的好处

  • 提高数据完整性:确保输入应用程序的数据有效且一致,减少错误和不一致。
  • 提高代码可读性和可维护性:声明性注释和自动验证使代码更具可读性且更易于管理。
  • 缩短开发时间:简化数据验证任务,使开发人员能够专注于核心应用程序逻辑。
  • 数据验证标准化方法:通过 JSR-303 跨所有 Java EE 平台的标准化方法。验证是可移植的并且可以重复使用。

了解 JSR-303 注释
JSR 303 bean 验证注释被定义为 javax.validation 包的一部分。一些重要的验证注释定义如下:
1. @NotNull:确保被注释的元素不为空。

public class Student {
    @NotNull(message = "学生姓名不能为空")
    private String name;< a i=3>}


2. @NotEmpty:检查字符串、集合、映射或数组是否不为空。

public class Student {
 @NotEmpty(message = "分数列表不能为空")
   private List
}

3. @Size 检查大小是否在指定边界之间。

public class Student {
    @Size(min = 18, message = "年龄不能小于")
    private String Age; 
}


4. @Min 和 @Max:限制数值属性的值,指定允许的最小或最大值。

public class Student {
 @Min(value = 1, message = "学生应至少注册一门科目")     
  @ Max(value = 4, message =
"学生不能注册超过四个科目")
 private double subject;
}

5. @Pattern:检查字符串是否与给定的正则表达式匹配。

public class Student {
    @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "请提供有效电话号码")
    private String phoneNumber;
}

6.@Email:检查字符串是否为有效的电子邮件地址。

public class Student {
    @NotNull
    @Email(message = "请提供有效的电子邮件地址")
    private String email;
}

7.@URL:检查字符串是否为有效的 URL。

public class Student {
    @URL(message = "请输入有效的网站")
    private String website;
}


9. @Future:检查日期/时间是否是未来。
例子:

public class Admin {
    @Future(message = "截止日期必须是将来的日期")
    private Date attendDueDate;
}

10. @DecimalMin 和@DecimalMax:检查十进制数范围。
例子:

public class Admin {
  @DecimalMin("100000.50")
  @DecimalMax(
"200000.00")
  private BigDecimal fees;
}

11. @Digits:检查整数或小数的位数。
例子:

public class Student {
  @Digits(integer = 5, fraction = 2)
  private double percentage;
}


12. @AssertTrue/False:检查布尔表达式是否为真/假。
例子:

public class Student { 
private int age; 

private boolean passedExam; 

@AssertTrue
public boolean isEligibleForScholarship() { 
    return age < 21 && passedExam; 

JSR-303依赖

<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency> 
    <groupId>javax.validation</groupId> 
    <artifactId>validation-api</artifactId> 
    <version>2.0.1.Final</version> 
</dependency>

对于依赖项,请使用此 URL Maven 存储库:https://mvnrepository.com/artifact/javax.validation/validation- API


Spring Bean 验证示例 – JSR-303 注释

需要:

  • Spring Web
  • Lombok
  • spring-boot-starter-validation

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns=
"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    <modelVersion>4.0.0</modelVersion> 
    <parent> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>3.2.0</version> 
        <relativePath/> <!-- lookup parent from repository -->
    </parent> 
    <groupId>com.spring</groupId> 
    <artifactId>Spring_JSR</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <name>Spring_JSR</name> 
    <description>Demo project for Spring_JSR</description> 
    <properties> 
        <java.version>17</java.version> 
    </properties> 
    <dependencies> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-web</artifactId> 
        </dependency> 
<dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-validation</artifactId> 
        </dependency> 
        <dependency> 
            <groupId>org.projectlombok</groupId> 
            <artifactId>lombok</artifactId> 
            <optional>true</optional> 
        </dependency> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-test</artifactId> 
            <scope>test</scope> 
        </dependency> 
    </dependencies> 

    <build> 
        <plugins> 
            <plugin> 
                <groupId>org.springframework.boot</groupId> 
                <artifactId>spring-boot-maven-plugin</artifactId> 
                <configuration> 
                    <excludes> 
                        <exclude> 
                            <groupId>org.projectlombok</groupId> 
                            <artifactId>lombok</artifactId> 
                        </exclude> 
                    </excludes> 
                </configuration> 
            </plugin> 
        </plugins> 
    </build> 

</project> 

使用 JSR 注解创建 Pojo 类 [学生]

package com.demo.model; 

import jakarta.validation.constraints.AssertTrue; 
import jakarta.validation.constraints.Digits; 
import jakarta.validation.constraints.Email; 
import jakarta.validation.constraints.Min; 
import jakarta.validation.constraints.NotBlank; 
import jakarta.validation.constraints.NotEmpty; 
import jakarta.validation.constraints.NotNull; 
import jakarta.validation.constraints.Pattern; 
import jakarta.validation.constraints.Size; 
import lombok.Data; 
import org.hibernate.validator.constraints.URL; 

@Data
public class Student { 
    @NotNull
    @Size(min = 3, max = 50, 
        message 
        = "Name must be between three to fifty characters"
    private String name; 

    @Email(message =
"Invalid email format"
    private String email; 

    @NotNull(message =
"Age cannot be null"
    @Min(value = 18, 
        message 
        =
"Age must be greater than or equal to eighteen"
    private Integer age; 

    @NotEmpty(message =
"Address cannot be empty"
    private String address; 

    @Pattern(regexp =
"\\d{10}"
            message =
"Phone number must be ten digits"
    private String phoneNumber; 

    public Student( 
        @NotNull
        @Size(min = 3, max = 50, 
            message 
            =
"Name must be between three to fifty characters"
        String name, 
        @Email(message 
            =
"Invalid email format") String email, 
        @NotNull(message =
"Age cannot be null"
        @Min(value = 18, 
            message 
            =
"Age must be greater than or equal to eighteen"
        Integer age, 
        @NotEmpty(message =
"Address cannot be empty"
        String address, 
        @Pattern(regexp =
"\\d{10}"
                message =
"Phone number must be 10 digits"
        String phoneNumber) 
    { 
        super(); 
        this.name = name; 
        this.email = email; 
        this.age = age; 
        this.address = address; 
        this.phoneNumber = phoneNumber; 
    } 
}

创建一个处理所有验证的控制器 [StudentController]

package com.demo.controller; 

import com.demo.model.Student; 
import jakarta.validation.Valid; 
import java.util.List; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.PostMapping; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 

@RestController
public class StudentController { 
    @PostMapping("/student"
    public String 
    createUser(@RequestBody @Valid Student student, 
            BindingResult bindingResult) 
    { 
        if (bindingResult.hasErrors()) { 
            return
"Validation errors: "
                + bindingResult.getAllErrors(); 
        } 

        return
"Student created successfully: "
            + student.toString(); 
    } 
}

运行应用程序

  • 现在您可以从 IDE 或命令行运行 spring boot 应用程序。

mvn spring-boot:run

使用curl、Postman等工具访问http://localhost:8080/students,您应该会看到课程页面。