springboot 校验注解Long长度
时间: 2023-07-04 20:14:36 浏览: 96
在Spring Boot中,可以使用JSR-303校验注解来校验Long类型的长度。具体步骤如下:
1. 引入JSR-303校验依赖,例如:
```xml
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
```
2. 在需要校验的Long类型属性上添加注解,例如:
```java
public class User {
@Size(min = 1, max = 10, message = "ID长度必须在1~10之间")
private Long id;
// ...
}
```
在上述示例中,@Size注解用于校验id属性的长度,min属性指定最小长度,max属性指定最大长度,message属性指定校验失败时的错误消息。
3. 在需要进行校验的方法或类上添加校验注解,例如:
```java
@RestController
@RequestMapping("/users")
@Validated
public class UserController {
@PostMapping
public void createUser(@Valid @RequestBody User user) {
// ...
}
}
```
在上述示例中,@Validated注解用于开启校验功能,@Valid注解用于校验请求体中的User对象,如果校验失败会抛出MethodArgumentNotValidException异常。
通过上述步骤,就可以在Spring Boot中使用JSR-303校验注解来校验Long类型的长度。