In previous post under MapStruct I showed with example how to add callback methods in abstract class used as Mapper interface.
In this post I will show with example how to add callback methods in interface used as Mapper Interface.
For our example I will take the below Pojo class
Student
package package19;
public class Student {
private int id;
private String name;
private String className;
//Removed getter and setter for brevity
}
StudentDTO
package package19;
public class StudentDTO {
private int id;
private String name;
private String className;
//Removed getter and setter for brevity
}
I have to map a “Student” object to “StudentDTO” object.
Below will be the Mapper interface
StudentMapper
package package19;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeforeMapping;
import org.mapstruct.Mapper;
@Mapper
public interface StudentMapper {
StudentDTO getDTOFromModel(Student student);
@BeforeMapping
public default void beforeMapping() {
System.out.println("Before Mapping");
}
@AfterMapping
public default void afterMapping() {
System.out.println("After Mapping");
}
}
As you can see from the above code I have added two default methods named “beforeMapping” annotated with “BeforeMapping” annotation and then “afterMapping” annotated with “AfterMapping” annotation.
Both the methods are just printing text to the console.
In this way we can add callback methods to interface when used as Mapper interface.
Below is the complete main code for your reference
Main class
package package19;
import org.mapstruct.factory.Mappers;
public class Example19 {
public static void main(String[] args) {
StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
Student student = new Student();
student.setClassName("X");
student.setName("John");
student.setId(1);
StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
System.out.println(studentDTO);
}
}