본문 바로가기
개발언어/SPRING

[SPRING] BeanUtils.copyProperties을 이용하여 Class간의 property 복사하기

by 코딩 시그널 2020. 3. 15.
반응형

오늘 회사에서 인쇄 기능을 구현하는데 3개의 객체 합쳐 1개의 객체로 데이터를 복사해야 되는 일이 생겼어요. 하지만 3개의 객체를 모두 합치면 필드 개수가 100개가 훨씬 넘는 상황이라 setter를 이용하는 대신 BeanUtils.copyProperties을 이용하여 쉽고 간결하게 코드를 구현할 수 있었습니다.

 

사용 방법

BeanUtils.copyProperties(source, target);

source : 원본 객체

target :  복사 대상 객체

 

public static void copyProperties(Object source, Object target) throws BeansException

Expain:    
Copy the property values of the given source bean into the target bean.Note: The source and target classes do not have to match or even be derived from each other, as long as the properties match. Any bean properties that the source bean exposes but the target bean does not will silently be ignored.This is just a convenience method. For more complex transfer needs, consider using a full BeanWrapper.

Parameters:
source - the source bean
target - the target bean

Throws:
BeansException - if the copying failedSee Also:BeanWrapper

 

import org.springframework.beans.BeanUtils;
public class Student {
	public static void main(String[] args) {
		StudentInfo st = new StudentInfo();
		st.setName("이현아");
		st.setGrade(1);
		StudentInfoTarget stTarget = new StudentInfoTarget();
		BeanUtils.copyProperties(st, stTarget);
	}
}
class StudentInfo{
	private String name;
	private int grade;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
}
class StudentInfoTarget{
	private String name;
	private int grade;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
}

 

setter 속성을 사용하는 경우 

stTarget.setName(st.getName()); 
stTarget.setGrade(st.getGrade()); 


BeanUtils을 이용하는 경우

BeanUtils.copyProperties(st, stTarget);

 

지금은 필드가 2개 밖에 되지 않아 copyProperties를 사용하는 경우와 별반 차이가 없지만 필드가 많은 경우라면 소스가 훨씬 간결해 지는 것을 볼 수 있습니다.

 

만약에 특정 필드의 복사를 원하지 않은 경우에는 아래와 같이 ignore부분에 필드명을 입력하면 그 필드는 복사되지 않습니다.

 

BeanUtils.copyProperties(source, target, String ... ignoreProperites);

source : 원본 객체

target : 복사 대상 객체

ignoreProperities : 복사를 원하지 않는 프로퍼티명

 

위의 예제 소스에 적용해 보면 age 복사를 원하지 않는 경우 아래와 같이 작성하면 됩니다.

BeanUtils.copyProperties(st, stTarget, "age");

 

 

BeanUtils.copyProperties에 대한 자세한 설명은 아래의 링크를 참조하세요

 

BeanUtils (Spring Framework 5.2.4.RELEASE API)

static boolean isSimpleValueType(Class  type) Check if the given type represents a "simple" value type: a primitive or primitive wrapper, an enum, a String or other CharSequence, a Number, a Date, a Temporal, a URI, a URL, a Locale, or a Class.

docs.spring.io

 

댓글