In this post under MapStruct, I will show with example how to add callback methods which will be executed before and after mapping, in abstract class used as Mapper interface.
We use two annotations “@BeforeMapping” and “@AfterMapping” to annotate methods which will be called before and after mapping.
Lets say for example I have to map “Student” object to “StudentDTO” object.
The mapper interface using abstract class will be as shown below
Mapper Interface
package package18;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeforeMapping;
import org.mapstruct.Mapper;
@Mapper
public abstract class StudentMapper {
abstract StudentDTO getDTOFromModel(Student student);
@BeforeMapping
public void beforeMapping() {
System.out.println("Before Mapping");
}
@AfterMapping
public void afterMapping() {
System.out.println("After Mapping");
}
}
As you can see from the above code, we have two methods “beforeMapping” annotated “@BeforeMapping” and “afterMapping” annotated with “@AfterMapping”
In this way we can add callback methods when using abstract class Mapper Interface.
Below is the “Student” and “StudentDTO” class structure for your reference
Student
package package18;
public class Student {
private int id;
private String name;
private String className;
//Removed getter, setter, and toString for brevity
}
StudentDTO
package package18;
public class StudentDTO {
private int id;
private String name;
private String className;
//Removed getter, setter, and toString for brevity
}
Below is the main method for your reference
Main class
package package18;
import org.mapstruct.factory.Mappers;
public class Example18 {
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);
}
}