본문 바로가기

Spring

[Spring] [ERROR] @RequiredArgsConstructor의 잘못된 사용으로 인한 NullPointerException

수정 전 코드

  • return insertActionWithReservationInfo.executeAndReturnKey(params).intValue(); 이 부분에서, insertActionWithReservationInfo가 np exception이 발생하였다. (디버깅으로 발견)
  • 문제는, 생성자 주입을 사용하면서 @RequiredArgsConstructor를 사용한 것이였다.
  • NamedParameterJdbcTemplate jdbc, SimpleJdbcInsertOperations insertActionWithReservationInfo 와 같은 객체들이 빈으로 등록되어있는 상황이 아닌데 @RequiredArgsConstructor를 사용하였기 때문에, np exception이 발생하였다.
@Repository
@RequiredArgsConstructor
public class ReservationInfoDao {

    private NamedParameterJdbcTemplate jdbc;
    private SimpleJdbcInsertOperations insertActionWithReservationInfo;
    private SimpleJdbcInsertOperations insertActionWithReservationInfoPrice;
    private RowMapper<ReservationInfoSaveResponse> rowMapper = BeanPropertyRowMapper.newInstance(ReservationInfoSaveResponse.class);

    public ReservationInfoDao(DataSource dataSource) {
        this.jdbc = new NamedParameterJdbcTemplate(dataSource);
        this.insertActionWithReservationInfo = new SimpleJdbcInsert(dataSource)
                .withTableName("reservation_info")
                .usingColumns("id","product_id","display_info_id","user_id","reservation_date") // 이걸로 지정해서 insert문 보내보기
                .usingGeneratedKeyColumns("id");

        this.insertActionWithReservationInfoPrice = new SimpleJdbcInsert(dataSource)
                .withTableName("reservation_info_price")
                .usingColumns("id","reservation_info_id","product_price_id","count") // 이걸로 지정해서 insert문 보내보기
                .usingGeneratedKeyColumns("id");
    }
    
        public int insertReservationInfo(ReservationInfo reservationInfo){
        Map<String, Object> params = new HashMap<>();
        params.put("id",null);
        params.put("productId", reservationInfo.getProductId());
        params.put("displayInfoId", reservationInfo.getDisplayInfoId());
        params.put("userId", reservationInfo.getUserId());
        params.put("reservationDate", reservationInfo.getReservationDate());
		
        // NullpointerException 발생
        return insertActionWithReservationInfo.executeAndReturnKey(params).intValue(); // np ex
    }
}

 

수정 후 코드

  • 위의 코드에서, @RequiredArgsConstructor만 삭제하면 정상동작한다.