在springboot中如何开启Bean数据校验

①:添加JSR303规范坐标与Hibernate校验框架对应坐标

java 复制代码
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

②:对Bean开启校验功能

java 复制代码
@Component
@Data
@ConfigurationProperties(prefix = "servers")
@Validated
public class ServerConfig {
}

③:设置校验规则

java 复制代码
@Component
@Data
@ConfigurationProperties(prefix = "servers")
@Validated
public class ServerConfig {
    @Max(value = 400,message = "最大值不能超过400")
    private int port;
}

小结: 1. 启用Bean属性校验 导入JSR303与Hibernate校验框架坐标

2.使用@Validated注解启用校验功能

3.使用具体校验规则规范数据校验格式

相关推荐
SamDeepThinking4 分钟前
函数式编程:用BiFunction消除多类型分支的代码重复
java·后端·面试
Flittly17 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了18 小时前
Java 生成二维码解决方案
java·后端
人活一口气1 天前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP1 天前
Vibe Coding -- 完整项目案例实操
java
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing1 天前
Google第三方授权登录
java·后端·程序员
明月光8181 天前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑1 天前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯1 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式