SpringBoot使用Validation框架手动校验对象是否符合规则

 

 

在springboot项目中引入

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

 

伪代码

import lombok.Data;
import lombok.experimental.Accessors;

import javax.validation.constraints.NotNull;


@Data
@Accessors(chain = true)
public class DemoEntity {

    private Long id;

    @NotNull
    private String name;
}

 

使用

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;


public class Test4 {

    public static void main(String[] args) {
        DemoEntity entity = new DemoEntity();
        entity.setId(1L);


        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        // 手动校验对象
        Set<ConstraintViolation<DemoEntity>> violations = validator.validate(entity);
        if (violations.isEmpty()) {
            System.out.println("对象值匹配");
        } else {
            for (ConstraintViolation<DemoEntity> violation : violations) {
                System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
            }
        }
    }
}

 

posted @ 2024-02-06 15:32  yvioo  阅读(112)  评论(0编辑  收藏  举报