开发经验总结

一、validation的使用

引入依赖

java 复制代码
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

采用注解校验

实体类的字段采用相关注解修饰,如@NotNull,@Null

java 复制代码
@NotBlank
private String name;

在controller使用@Valid修饰该实体类

分组校验

(1)定义一个标识接口

java 复制代码
public interface Add {}

(2)在校验注解指定分组

java 复制代码
@Null(groups = Add.class)

(3)使用Validated修饰实体类

java 复制代码
@Validated(Add.class)

注意:当使用分组校验时,修饰字段的注解都要加分组,否则其他字段校验不生效,它只会在Validated修饰

自定义校验注解

(1)编写一个自定义注解

java 复制代码
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = {ShowConstraintValidator.class}//可以指定多个校验器
)
public @interface Show {
    //默认消息提示,需要在resources目录下新增ValidationMessages.properties配置
    String message() default "{com.mall.common.valid.Show.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    int[] vals() default {};

}

(2)在自定义一个校验器

java 复制代码
public class ShowConstraintValidator implements ConstraintValidator<Show,Integer> {
    @Override
    public void initialize(Show constraintAnnotation) {
       //初始化参数
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        //todo 校验逻辑判断
        return true;
    }
}

(3)在resources目录增加一个配置文件ValidationMessages.properties

java 复制代码
com.mall.common.valid.Show.message=test
相关推荐
二哈赛车手2 分钟前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
代码搬运媛4 分钟前
Jest 测试框架详解与实现指南
前端
栗子~~42 分钟前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
YDS8291 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
counterxing1 小时前
我把 Codex 里的 Skills 做成了一个 MCP,还支持分享
前端·agent·ai编程
wangqiaowq1 小时前
windows下nginx的安装
linux·服务器·前端
之歆1 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
发现一只大呆瓜2 小时前
Vite凭什么这么快?3分钟带你彻底搞懂 Vite 热更新的幕后黑手
前端·面试·vite
Maimai108082 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
未若君雅裁2 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis