将一个对象中值复制到另外一个新对象中的工具: MapStruct ,使用方式:
1. 加入依赖:
1.3.0.Final
...
org.mapstruct
mapstruct
${org.mapstruct.version}
org.mapstruct
mapstruct-processor
${org.mapstruct.version}
org.springframework.boot
spring-boot-maven-plugin
1.8
1.8
org.mapstruct
mapstruct-processor
${org.mapstruct.version}
原始类:
public class CloneDTO {
private String strVal;
private Integer intVal;
private int intVal2;
// Default constructor, getter/setters...}
接口:
@Mapper(componentModel = “ spring ”)
public interface Cloner {
public CloneDTO clone(CloneDTO dto);
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ClonerTests {
@Autowired
Cloner mapper;
@Test
public void contextLoads() {
CloneDTO dto = new CloneDTO("1", 2, 3);
CloneDTO obj = mapper.clone(dto);
assertThat(obj.getStrVal()).isEqualTo("1");
assertThat(obj.getIntVal()).isEqualTo(2);
assertThat(obj.getIntVal2()).isEqualTo(3);
assertThat(dto.hashCode()).isNotEqualTo(obj.hashCode());
}
}