Hanbit the Developer

[Spring Boot] @NoArgsConstructor(access = AccessLevel.PROTECTED) 사용 이유 본문

Back-end

[Spring Boot] @NoArgsConstructor(access = AccessLevel.PROTECTED) 사용 이유

hanbikan 2024. 7. 9. 18:09

 

아래 코드에서 왜 굳이 PROTECTED로 access modifier를 두는 것이 권장되는가?

@Entity
@Table(name = "account")
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Account {
    @Id
    @GeneratedValue
    private long id;

    private String email;

    // ...
}

이유 1: JPA 요구사항

JPA 문서에 의하면 entity 클래스는 public/protected no-argument constructor가 있어야 한다고 한다.

• The class must have a public or protected, no-argument constructor. The class may have other constructors.

이유 2: 캡슐화

선택지가 public or protected가 남는데, protected로 권한을 최소화하여 오사용을 방지하는 것이 좋다고 생각한다.

References

https://docs.oracle.com/javaee/6/tutorial/doc/bnbqa.html

https://velog.io/@kevin_/내가-NoargsConstructor-access-AccessLevel.PROTECTED를-왜-작성했을까