[SpringBoot]BeanUtils.copyProperties()

해니·2025년 7월 4일
0

SpringBoot

목록 보기
25/25
post-thumbnail

반복적인 set을 줄이려면.. ❔

  • 기존 코드는 쿼리문 결과를 담은 result 객체 자체에서 특정 멤버 변수만 set하고 있었다.
  • 1차로 쿼리문 결과를 담는 객체는 result로, 메서드 응답 타입은 response객체로 분리했다
  • 분리 후에 result 객체의 멤버 변수를 하나씩 get()하고 response객체에 set()하는 로직이 너무 번거롭고 유지보수가 힘들 것 같아 리팩토링 진행 도중에 BeanUtils 클래스를 이용하게 되었다.



BeanUtils.copyProperties()

copyProperties(Object source, Object target, String... ignoreProperties)
  • org.springframework.beans 패키지에 있는 BeanUtils 클래스
  • source : 원본 객체
  • target : 복사 객체
  • ignoreProperties : 복사하지 않을 필드명들



주의 사항 ⚠️

  1. copyProperties()Reflection을 이용하여 get() set() 함수를 조회하여 구현하였기 때문에, source(원본객체)는 get() 메서드가 필수이며, target(복사객체)은 set() 함수가 필수다.
  2. target에 있는 변수와 동일한 source의 변수 값이 null인 경우 오류가 발생한다.
  3. import시, springframework.beans.BeanUtilsapache.commons.beanutils.BeanUtils의 파라미터 위치가 다르므로 주의해야 한다.






출처

[Spring]BeanUtils.copyProperties를 사용해보자
[Java][Spring]BeanUtils.copyProperties() 정리 및 주의점

profile
💻 ⚾️ 🐻

0개의 댓글