<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.2.Final</version>
</dependency>
public class SourceObject {
private String name;
private int age;
// Getters and Setters
}
public class TargetObject {
private String fullName;
private int years;
// Getters and Setters
}
@Mapper
public interface ObjectMapper {
ObjectMapper INSTANCE = Mappers.getMapper(ObjectMapper.class);
@Mappings({
@Mapping(target = "fullName", source = "name"),
@Mapping(target = "years", source = "age")
})
TargetObject sourceToTarget(SourceObject source);
}
SourceObject source = new SourceObject();
source.setName("John");
source.setAge(30);
TargetObject target = ObjectMapper.INSTANCE.sourceToTarget(source);
System.out.println(target.getFullName()); // Output: John
System.out.println(target.getYears()); // Output: 30
@Mapper
public interface ObjectMapper {
ObjectMapper INSTANCE = Mappers.getMapper(ObjectMapper.class);
@Mappings({
@Mapping(target = "fullName", source = "name"),
@Mapping(target = "years", source = "age", qualifiedBy = AgeConverter.class)
})
TargetObject sourceToTarget(SourceObject source);
@Named("AgeConverter")
static int convertAge(int age) {
return age * 2;
}
}