
객체를 값마다 돌면서 set하는 게 아니라, 간편하게 처리할 수 있는 방법을 알아내서 코드에 바로 적용해보았다.
코드가 한결 깔끔하고 보기 좋아졌음 🙌🙌
.copyProperties에 대한 설명 시작합니다!
copyProperties()는 Spring Framework의 BeanUtils 클래스에 있는 메서드로, 하나의 객체에서 다른 객체로 필드 값을 복사할 때 사용된다. 주로 두 객체 간에 같은 필드 이름과 타입을 가진 경우에 유용하게 사용할 수 있다. 이 메서드를 사용하면 객체의 특정 필드들을 일일이 복사하지 않고 한 번에 처리할 수 있어 코드를 간결하게 유지할 수 있다.
import org.springframework.beans.BeanUtils;
public class Main {
public static void main(String[] args) {
SourceObject source = new SourceObject();
source.setName("John");
source.setAge(30);
TargetObject target = new TargetObject();
BeanUtils.copyProperties(source, target);
System.out.println(target.getName()); // "John"
System.out.println(target.getAge()); // 30
}
}
위 코드에서 BeanUtils.copyProperties(source, target)를 사용하면 source 객체의 name과 age 값이 target 객체로 복사된다.
null일 경우, 타깃 객체의 필드 값도 null로 덮어씌워진다.copyProperties()는 특정 필드를 제외하고 복사할 수도 있다. 예를 들어, 특정 필드는 복사하고 싶지 않을 때 ignoreProperties 매개변수를 사용할 수 있다.
BeanUtils.copyProperties(source, target, "age");
위 코드는 age 필드를 제외하고 나머지 필드를 복사한다.
copyProperties()는 필드에 직접 접근하는 것이 아니라 getter와 setter 메서드를 통해 값을 복사한다. 따라서 필드에 대한 getter/setter가 정의되어 있어야 한다.copyProperties()는 주로 다음과 같은 상황에서 유용하다.
copyProperties()로 쉽게 처리할 수 있다.UserDTO userDTO = new UserDTO();
userDTO.setName("John");
userDTO.setAge(30);
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(userDTO, userEntity);
Spring의 copyProperties()를 사용하면 객체 간의 데이터 전송이 훨씬 간결해지고, 반복되는 코드를 줄일 수 있다.