BeanUtils.copyProperties [BeanUtils.copyProperties] for Spring (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html#copyProperties-java.lang.Object-java There is a convenient method called .lang.Object-). It's a method that copies the contents of a field with the same name from one bean to the other. The first argument is the copy source and the second argument is the copy destination. Even if the classes are different, copying is possible if they have the same field name.
** Book
class **
public class Book {
String code;
String name;
int price;
}
Example of use
Book book1 = new Book();
book1.setCode("A");
book1.setName("Three Kingdoms");
book1.setPrice(500);
Book book2 = new Book();
BeanUtils.copyProperties(book1, book2);
By doing this, the code
, name
, and price
values of book1
are copied to book2
in their entirety.
For example, suppose you have the following Form and Dto.
** CreateBookForm ** class
public class CreateBookForm {
String code;
String name;
int price;
}
** BookDto ** class
public class BookDto {
String code;
String name;
int price;
String updateModule;
}
Innocently writing BeanUtils.copyProperties (createBookForm, bookDto)
etc. in the Form-> Dto mapping will increase the mortality rate.
Suppose the field name of CreateBookForm
is changed from code
to cd
due to the convenience of the front end.
** CreateBookForm ** class (after change)
public class CreateBookForm {
String cd;
String name;
int price;
}
This no longer copies cd-> code
. This is because the field names are different.
Then you should change the field name of BookDto
! There may be an opinion, but it is not cool that the changes affect each other in the class prepared for layer separation.
When using this method, I think the following principles should be adhered to.
--Do not copy objects of different classes! There is no guarantee that the field name will not change forever! However, classes with inheritance relationship are excluded. --If you really need to copy objects of different classes, write a unit test to make sure they are copied!
This method, with the exact same name, is the Apache Commons Library (https://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties-java.lang) It exists in .Object-java.lang.Object-). Moreover, this method, ** the second argument is the copy source and the first argument is the copy destination **. Spring's method with the same name and the order of its arguments are reversed! !! Note that when using library auto-import in the IDE, some classes may call Spring and some classes may call Apache's copyProperties, which can be unnoticed. I was addicted to it.
Personally, I have a strong impression of "from left to right = from first argument to second argument" in "copy source-> copy destination", so I always use Spring ones.
Recommended Posts