@Getmapping + @RequestParam은 WebDataBinder를 사용합니다.
WebDataBinder는 기본 생성자와 Getter, Setter가 필수 입니다.
그러므로 record를 사용할 수 없습니다 class형식 사용이 불가피 합니다.(setter 사용 불가)
그리고 처음 의도는 cusor를 제네릭으로 설정해 범용성 있게 PostCursorPageRequest를 사용하고자 했었습니다.
public static class PostCursorPageRequest<T> { private T cursor; private Integer size; public PostCursorPageRequest(T cursor, Integer size) { this.cursor = cursor; this.size = size; } public T getCursor() { return cursor; } public Integer getSize() { return size; } public void setCursor(T cursor) { this.cursor = cursor; } public void setSize(Integer size) { this.size = size; } }
하지만 어째서인지 아래와 같이 ClassCastException이 발생합니다.
[2022-07-06 00:47:22:1349543] [http-nio-8080-exec-1] WARN c.k.i.e.CommonRestControllerAdvice ?.?.? :java.lang.ClassCastException: class java.lang.Object cannot be cast to class com.kdt.instakyuram.article.post.domain.PostPagingCursor (java.lang.Object is in module java.base of loader 'bootstrap'; com.kdt.instakyuram.article.post.domain.PostPagingCursor is in unnamed module of loader 'app') java.lang.ClassCastException: class java.lang.Object cannot be cast to class com.kdt.instakyuram.article.post.domain.PostPagingCursor (java.lang.Object is in module java.base of loader 'bootstrap'; com.kdt.instakyuram.article.post.domain.PostPagingCursor is in unnamed module of loader 'app')
바인딩을 하긴하지만 PostPagingCursor 형식이아닌 Object형식으로 바인딩을 하기 때문에 캐스팅 예외가 발생한 것 이었습니다.
어쩔 수 없이 제네릭은 포기해야 했고 처음에 쓰고자한 record도 사용하지 못했습니다.
대신 WebDataBinder를 필드 주입 방식으로 설정해 setter 없이도 사용 가능 합니다 (getter는 여전히 있어야함)
@ControllerAdvice public class WebControllerAdvice { @InitBinderpublic void initBinder(WebDataBinder binder) { binder.initDirectFieldAccess(); } }