[Spring] Entity에 protected 생성자를 만드는 이유(@Noargsconstructor)

    [Spring] Entity에 protected 생성자를 만드는 이유(@Noargsconstructor)

    기본 생성자의 접근제어를 Protected로 설정해놓게 되면 무분별한 객체 생성에 대해 한번 더 체크할 수 있기 때문입니다.

    예시)

    @Getter
    @Setter
    @NoArgsConstructor
    public class User{
    	private Long id;
        private String name;
        private Long age;
        private String email;
    }
    
    public static void main(String[] args){
    	User user = new User();
        user.setName("이름1");
        user.setEmail("이메일1");
    }

    위 User 클래스와 main 함수를 보면 이름과 이메일만 setter를 사용해 값을 설정해준것을 볼 수 있는데

    이렇게 될 경우 age값이 누락되어 불완전한 객체가 되어버린다.

     

    @Getter
    @NoArgsConstructor(access = AccessLevel.PROTECTED)
    public class User{
    	private Long id;
        private String name;
        private Long age;
        private String email;
        
        public User(String name, String email){
        	this.name = name;
            this.email = email;
            this.age = 30L;
        }
    }
    
    public static void main(String[] args){
    	User user = new User("이름1", "이메일1");
    }

    @Setter를 없애고 생성자를 통해 객체를 생성하게되어 무조건 완전한 상태의 객체가 생성되게된다.

     

    AccessLevel을 PRIVATE으로 하게 될 경우

    JPA 표준 스펙에 디폴트 생성자가 있어야하므로 Private이 될 수 없으며,

    JPA가 프록시 기술을 쓸때, Jpa hibernate가 객체를 강제로 만들어야 하는데 private로 만들면 이게 다 막히기 때문이기도 하다.

    그래서 protected 생성자를 사용하는 편이다.

    댓글

    Designed by JB FACTORY