Json工具是通过序列化反序列化来实现的,性能低下。
MapStruct是通过getter、setter来实现的。
<!--MapStruct依赖-->
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-processor -->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.0.0.Final</version>
</dependency>
使用
@Data
@Builder
public class User {
private String uname;
private Integer uid;
private String uaddr;
}
@Data
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
private String name;
private Integer id;
private Integer updateUserId;
}
由Spring代理
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring") //表示由Spring代理
public interface UserMapping {
//UserMapping USERMAPOING = Mappers.getMapper(UserMapping.class); //可以不要
/*
将user的uname映射成目标类userDto的name字段
...
*/
@Mapping(target = "name",source = "uname")
@Mapping(target = "id",source = "uid")
UserDto userToUserDto(User user);
}
使用
@Resource
private UserMapping userMapping;
public void func(){
User user = User.builder()
.uname("zhangsan")
.uid(22)
.build();
UserDto userDto = userMapping.userToUserDto(user);
}
不由spring代理
@Mapper
public interface UserMapping {
UserMapping USERMAPOING = Mappers.getMapper(UserMapping.class);
@Mapping(target = "name",source = "uname")
@Mapping(target = "id",source = "uid")
UserDto userToUserDto(User user);
}
@Test
public void t1(){
User user = User.builder()
.uname("zhangsan")
.uid(22)
.build();
UserDto userDto = UserMapping.USERMAPOING.userToUserDto(user);
userDto.setUpdateUserId(111);
log.info(userDto.toString());
}
其它属性
ignore
@Mapping(target = “age”, ignore = true)
添加了ignore,表示不会对该属性做映射;
原理
MapStruct生成了mapping的实现类,通过调用get\set实现;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2021-04-30T12:58:59+0800",
comments = "version: 1.0.0.Final, compiler: javac, environment: Java 1.8.0_211 (Oracle Corporation)"
)
@Component
public class UserMappingImpl implements UserMapping {
@Override
public UserDto userToUserDto(User user) {
if ( user == null ) {
return null;
}
UserDto userDto = new UserDto();
userDto.setName( user.getUname() );
userDto.setId( user.getUid() );
return userDto;
}
}