히콩쓰 개발 일지
Primitive Type(원시타입)과 Wrapper Class(래퍼 클래스) 의 Getter 본문
문제 분석
To-Do List를 개발하던 도중, "완료 된 할일 인가?" 를 표현하기 위해 아래와 같은 코드를 작성하였다.
public class Card extends Timestamped{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "card_id")
@Getter
private Long cardId;
@Getter
private String cardTitle;
@Getter
private String cardContent;
@Getter
private boolean isCompletion;
이 때, private boolean isCompletion
이라는 필드에서 문제를 겪었다.
아래는 Service에서 전체 카드를 조회하도록 구현한 코드이다. 오류가 발생하는 것을 확인할 수 있다.
하지만 자동완성 기능을 이용해보면, 아래와 같이 isCompletion() 으로 작성해주고, 더이상 오류가 발생하지 않는다.
무엇이 문제인가 싶을 수 있지만, for문을 보면 Dto에 add 하는 부분에서 다른 것은 모두 "get"이라는 접두사로 시작하는데 isCompletion
이라는 필드만 "get" 접두사로 시작하지 않는 것을 확인할 수 있다.
여기서 든 생각은, 아래 두 가지 이다.
isCompletion
은private
인데 어떻게 저렇게 접근했는가?- 변수명을 저렇게 설정한 것이 내부적으로 내가 모르는 로직을 거친건가? 왜
isCompletion
만 get으로 접근이 안되지?
문제 해결
문제 원인을 알기 위해 구글링 해보니, Primitive Type
과 Wrapper Class
의 Getter 표현방식 차이였다.
Primitive Type
은 Getter가 "is" 접두사를 사용한다.Wrapper Class
는 Getter가 "get" 접두사를 사용한다.
isCompletion
이라는 변수는 boolean
이므로 get.속성
으로 접근할 수 없었던 것이다.
따라서, 아래와 같이 코드를 수정하였다.
public class Card extends Timestamped{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "card_id")
@Getter
private Long cardId;
@Getter
private String cardTitle;
@Getter
private String cardContent;
@Getter
private Boolean isCompletion;
그리고, Service 에서도 정상적으로 get으로 속성값을 가져올 수 있었다.
// 전체 카드 조회
public CardViewAllResponseDto viewAllCard(){
List<Card> cardList = cardRepository.findAll();
CardViewAllResponseDto cardViewAllResponseDto = new CardViewAllResponseDto();
for (Card c : cardList) {
cardViewAllResponseDto.add(c.getCardId(), c.getCardTitle(), c.getUser().getUserName(),
c.getCreatedAt(), c.getIsCompletion());
}
return cardViewAllResponseDto;
}
실제로 getIsCompletion으로 오류 없이 값을 가져오는 것을 확인할 수 있다!
+ 그렇다면 왜 isCompletion이라는 변수를 Getter로 가져오는데 isisCompletion이 아니었는가...? 에 대해서는 차차 찾아보고 정리해보도록 하겠다....
'Spring' 카테고리의 다른 글
[Spring Security] 권한을 올바르게 설정했는데 403 에러가 날 경우 고려해야 할 점 (2) | 2023.12.12 |
---|---|
Controller Test 403 forbidden 해결 (1) | 2023.12.05 |
Spring Boot 프로젝트 Dto 사용 시 HTTP 406 Error 해결 방법! (0) | 2023.11.21 |
@ReqestBody String 사용 시 Json이 그대로 입력되는 이유 (1) | 2023.11.14 |
[Consider declaring it as object wrapper for the corresponding primitive type] 발생 원인과 해결 방법 (0) | 2023.11.10 |