// 引入MapStruct依赖
// 在pom.xml中添加以下依赖:
/*
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.2.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.2.Final</version>
<scope>provided</scope>
</dependency>
*/
// 定义源对象和目标对象
public class Source {
private String id;
private String name;
// getters and setters
}
public class Target {
private String id;
private String fullName;
// getters and setters
}
// 定义Mapper接口
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "fullName")
Target sourceToTarget(Source source);
}
// 使用Mapper进行转换
public class Main {
public static void main(String[] args) {
Source source = new Source();
source.setId("1");
source.setName("John Doe");
Target target = SourceTargetMapper.INSTANCE.sourceToTarget(source);
System.out.println("ID: " + target.getId());
System.out.println("Full Name: " + target.getFullName());
}
}
pom.xml中添加MapStruct的依赖,确保项目可以使用MapStruct的功能。Source和Target,分别表示源对象和目标对象。这两个类包含不同的属性,但可以通过映射规则进行转换。@Mapper注解定义一个接口SourceTargetMapper,并在其中声明一个方法sourceToTarget,该方法用于将Source对象转换为Target对象。通过@Mapping注解指定具体的属性映射规则。Main类中,创建一个Source对象并设置其属性,然后使用SourceTargetMapper.INSTANCE.sourceToTarget方法将其转换为Target对象,并输出结果。这样,你就可以使用MapStruct轻松地在不同对象之间进行属性映射了。
上一篇:java divide函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站