Using @ObjectFactory annotation to create target objects

In this post under MapStruct, I will explain with example the purpose of “@ObjectFactory” annotation.

Till now in all my previous post, I have shown you that MapStruct uses constructor and builder method to create target objects.

We can also create an object using factory methods.

To instruct MapStruct to stop using constructor, buider method and use factory method instead, we need to annotate the factory method with “@ObjectFactory” annotation.

Note the factory method which is annotated with “@ObjectFactory” annotation should not take any parameters. So it should be parameterless method.

For our example, we will map “Student” to “StudentDTO” and use “createStudentDTO” factory method to create an instance of “StudentDTO” instance.

Below is the class structure of “Student” and “StudentDTO” class.

Student

package package30;

public class Student {
    private int id;
    private String name;
    private String className;

    //Removed getter and setter for brevity
}

StudentDTO

package package30;

public class StudentDTO {
    private int id;
    private String name;
    private String className;

    public StudentDTO() {
        System.out.println("Calling object constructor");
    }

    //Removed getter and setter for brevity
}

Below is the mapper interface

StudentMapper

package package30;

import org.mapstruct.Mapper;
import org.mapstruct.ObjectFactory;

@Mapper
public interface StudentMapper {
    StudentDTO getDTOFromModel(Student student);

    @ObjectFactory
    public default StudentDTO createStudentDTO() {
        System.out.println("Using factory instead of constructor");
        return new StudentDTO();
    }
}

In the above interface, I have added object factory method named “createStudentDTO” which will create an instance of “StudentDTO” class.

I have annotated this “createStudentDTO” factory method with “@ObjectFactory” annotation.

Below is the main class for your reference.

Main class

package package30;

import org.mapstruct.factory.Mappers;

public class Example30 {
    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);
    }
}

When we run this program, MapStruct uses factory method to create the object.

Below is the output for your reference

Output

Using factory instead of constructor
Calling object constructor
1:John:X

In this way we can instruct MapStruct to use object factory methods to call instead of constructor.

Leave a comment