Spring Boot 工程常见开发技巧

service 层参数 @Valid 校验

在 Spring Boot 工程中,一般开发中会 controller 层的接口参数的请求体对象属性中增加注解校验。在 service 层中,也可以对其进行 @Valid 注解校验:

在 service 接口实现类中增加 @Validated 注解,并在需要校验参数实体前增加 @Valid 注解即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;

/**
* @author woodwhales
* @date 2020-12-26 17:17
*/
@Service
@Validated
public class TempServiceImpl implements TempService {

@Override
public void save(@Valid TempData tempData) {
System.out.println(tempData);
}

}

参数实体对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
* @author woodwhales
* @date 2020-12-26 17:18
*/
@Data
public class TempData {

@NotNull
private Integer id;

@NotBlank
private String name;

}

controller 调用时,springboot 自动帮我们做了属性校验:

1
2
3
4
5
6
7
8
9
10
11
@RestController
public class TemController {

@Autowired
private TempService tempService;

@GetMapping("/temp")
public void temp() {
tempService.save(new TempData());
}
}
updated updated 2024-01-05 2024-01-05
本文结束感谢阅读

本文标题:Spring Boot 工程常见开发技巧

本文作者:

微信公号:木鲸鱼 | woodwhales

原始链接:https://woodwhales.cn/2020/12/26/078/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%