Reputation: 2814
is there a way to map a DTO using MatStruct which have a few final data members as well and cannot have a default constructor , like :
public class TestDto {
private final String testName;
private int id;
private String testCase;
public TestDto(String testName) {
this.testName = testName;
}
public String getTestName() {
return testName;
}
public int getId() {
return id;
}
public String getTestCase() {
return testCase;
}
public void setId(int id) {
this.id = id;
}
public void setTestCase(String testCase) {
this.testCase = testCase;
}
}
please suggest how could this DTO be mapped using MapStruct.
Upvotes: 1
Views: 2756
Reputation: 21423
You can use @ObjectFactory that would construct an instance of your DTO.
For example:
@Mapper
public interface MyMapper {
@ObjectFactory
default TestDto create() {
return new TestDto("My Test Name");
}
//the rest of the mappings
}
You can also enhance the @ObjectFactory
to accept the source parameter, that you can use to construct the TestDto
. You can even use a @Context
as an Object Factory.
NB: You don't have to put the @ObjectFactory
method in the same Mapper, or even a MapStruct @Mapper
. You can put it in any class (or make it static) and then @Mapper(uses = MyFactory.class)
Upvotes: 3