728x90
객체를 필드값을 복사하는 방법은 여러가지가 있다. 그 중에서 스프링부트가 제공하는 두가지를 간단하게 소개하려한다.
첫번째는 BeanUtils.copyProperties 를 활용하는 방법이다.
@Test
void BeanUtils_를_활용() {
Test1 test1 = new Test1("123","1234","1235","1236","1237","1238");
Test1 test2 = new Test2();
Long start1 = System.currentTimeMillis();
BeanUtils.copyProperties(test1,test2);
Long end1 = System.currentTimeMillis();
System.out.println("test2 = " + test2);
System.out.println("total time : " + (end1-start1));
}
출력물
test2 = Test2{id='123', num='1234', name='1235', email='1236', phoneNum='1237', addr='1238'}
total time : 1
두번째는 ObjectMapper 를 활용해 json 으로 변환후 다시 객체로 변환하는 작업이다.
(ObjectMapper 는 사실 객체를 복사하기보다는 json 형태로 외부에 제공할때 사용하는 것이지만, ObjectMapper 로 깊은 복사를 진행하는 경우를 보았기에 BeanUtils와 비교를 해보려한다.)
@Test
void ObjectMapper_를_활용() throws JsonProcessingException {
Test1 test3 = new Test3("123","1234","1235","1236","1237","1238");
Test1 test4 = new Test4();
Long start2 = System.currentTimeMillis();
ObjectMapper objectMapper = new ObjectMapper();
String asString = objectMapper.writeValueAsString(test3);
test4 = objectMapper.readValue(asString, Test1.class);
Long end2 = System.currentTimeMillis();
System.out.println("test4 = " + test4);
System.out.println("total time : " + (end2-start2));
}
출력물
test4 = Test4{id='123', num='1234', name='1235', email='1236', phoneNum='1237', addr='1238'}
total time : 55
당연한 결과겠지만, json 으로의 변환작업을 한번 더 거치는 ObjectMapper 가 더 걸리는 것을 볼 수 있다.
BeanUtils.copyProperties 를 사용할 때는 getter 와 setter 가 반드시 있어야한다.
다음은 BeanUtils.copyProperties 의 복사할 수 있는 필드에 대한 주의 사항이다.
source property type | target property type | copy supported |
Integer | Integer | yes |
Integer | Number | yes |
List<Integer> | List<Integer> | yes |
List<?> | List<?> | yes |
List<Integer> | List<?> | yes |
List<Integer> | List<? extends Number> | yes |
String | Integer | no |
Number | Integer | no |
List<Integer> | List<Long> | no |
List<Integer> | List<Number> | no |
728x90
'Project > Table_of_Organization_Management_System' 카테고리의 다른 글
NEXUS - 사용해보기 (0) | 2022.06.11 |
---|---|
버전관리 project version - Semantic Versioning (0) | 2022.06.10 |
Gradle Multi-Module구성하기 (0) | 2022.04.30 |
MySQL SQL 예약어를 확인하자 (0) | 2022.04.22 |
@EqualsAndHashCode (0) | 2022.04.20 |