领域对象之间的转换很常见,之前有几次用BeanUtil在某些时候漏掉一些字段,而且也不够灵活,所以就没在用。 然后基本都是手写convert类,但是多了就觉得很麻烦。。。 后来发现了mapstruct
maven依赖
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
</dependency>
看一下如何使用吧: 首先写两个类A和B
@Data
public class A {
private String name;
private int age;
private Date date;
}
@Data
public class B {
private String username;
private int age;
private String date;
}
转换类接口TestConverter,通过@Mapping注解可以比较灵活的定制自己想要的转换方式
@Mapper
public interface TestConverter {
TestConverter INSTANCE = Mappers.getMapper(TestConverter.class);
@Mappings({
@Mapping(source="name", target="username"),
@Mapping(source="age", target="age"),
@Mapping(source="date", target="date",dateFormat="yyyy-MM-dd HH:mm:ss")
})
B convertA2B(A a);
}
然后重新构建maven项目
mvn clean compile
会自动生成一个TestConverter的实现类
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-10-10T16:55:44+0800",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_201 (Oracle Corporation)"
)
public class TestConverterImpl implements TestConverter {
@Override
public B convertA2B(A a) {
if ( a == null ) {
return null;
}
B convertB = new B();
if ( a.getDate() != null ) {
convertB.setDate( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format( a.getDate() ) );
}
convertB.setAge( a.getAge() );
convertB.setUsername( a.getName() );
return convertB;
}
}
接下来就可以调用了
public static void main(String[] args) {
A a = new A();
a.setAge(13);
a.setName("luke");
a.setDate(new Date());
B b = TestConverter.INSTANCE.convertA2B(a);
System.out.println(JSON.toJSONString(b));
}
查看打印结果:
{"age":13,"date":"2019-10-10 17:00:32","username":"luke"}
原文出处:https://www.cnblogs.com/feng07/p/11649430.html
来源:oschina
链接:https://my.oschina.net/u/4387124/blog/3250785