Spring Validation Annotation on Class

Hyuk4316·2025년 6월 13일
0

Java Spring

목록 보기
5/5
post-thumbnail

Jackson과 Jakarta 라이브러리

기본적으로 Spring Boot를 활용할 때 JSON 형태의 데이터를 Jackson이 (DTO)객체로 변환해주어 편하게 사용할 수 있게 해준다. 또한 jakarta validation을 이용하면 DTO 객체의 데이터를 쉽게 검증해준다.

@PostMapping("/")
@ResponseStatus(HttpStatus.OK)
public DTO test(@RequestBody @Valid DTO dto) {
	return dto;
}
@Data
@NotNull
public class DTO {
	@NotNull
	private String s1;
	@NotNull
	private String s2;
	@NotNull
	private Integer n1;
	@NotNull
	private Integer n2;
}

의문점, 실험

여기서 jarkarta validation constraints anntations을 살펴보면 @TargetTYPE_USE를 확인할 수 있는데 이는 class와 interface에 annotation을 붙일 수 있는 것을 의미한다.

만약 DTO 클래스에 해당 annotation을 붙이면 검증 과정이 동작하는지 궁금했다.

@Data
@NotNull
public class DTO {
	private String s1;
	private String s2;
	private Integer n1;
	private Integer n2;
}

결론적으로 validation이 동작하지 않았고 field 값이 null을 가진채로 값을 리턴되었다.

curl 요청 결과

curl ~~~ -d '{"s1": "1", "s2": "2", "n1": 1}' http://localhost:8080/
{"s1":"1","s2":"2","n1":1,"n2":null}
profile
한국공학대학교 소프트웨어전공 23학번

0개의 댓글