In this post under MapStruct, I will explain with example the purpose of “defaultExpressions”.
Default expressions are the expressions that are executed with the source attribute is null.
I have introduced you to expressions in MapStruct in previous posts.
Till now we were using expressions without the source attribute.
But in case of default expressions we need to mention the source attribute.
The default expression is evaluated only if the source attribute is null.
For our example lets do the mapping from “Student” to “StudentDTO” class instance.
Below are the class structure of “Student” and “StudentDTO” class.
Student
package package27;
import java.util.Date;
public class Student {
private int id;
private String name;
private Date doj;
//Removed getter, setter, and toString for brevity
}
StudentDTO
package package27;
import java.util.Date;
public class StudentDTO {
private int id;
private String name;
private Date doj;
//Removed getter, setter, and toString for brevity
}
Below is the mapper interface configuring how the mapping should be done from “Student” to “StudentDTO”.
Mapper Interface
package package27;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
@Mapper
public interface StudentMapper {
@Mapping(target = "doj", source = "doj", defaultExpression = "java(new java.util.Date())")
StudentDTO getDTOFromModel(Student student);
}
In the above code, at line 8, we mentioned the source property “doj” which has to be mapped to destination property with same name.
If in a particular case, if source “doj” is null, the expression set in “defaultExpression” attribute is executed, which assigns the current date to destination property with same name.
If source “doj” is not null, then the value of source “doj” is set to destination property with same name.
Below is the main class for your reference
Main class
package package27;
import org.mapstruct.factory.Mappers;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Example27 {
public static void main(String[] args) {
StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
Student student = new Student();
student.setDoj(null);
student.setName("John");
student.setId(1);
StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
System.out.println("StudentDTO with null source doj-->" + studentDTO);
LocalDateTime localDateTime = LocalDateTime.of(2025, 1, 1, 12, 0, 0);
// Convert to java.util.Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
student = new Student();
student.setId(2);
student.setName("Jane");
student.setDoj(date);
studentDTO = studentMapper.getDTOFromModel(student);
System.out.println("StudentDTO with not null source doj-->" + studentDTO);
}
}
Below is the output
Output
StudentDTO with null source doj-->1:John:Fri Aug 15 09:40:15 IST 2025
StudentDTO with not null source doj-->2:Jane:Wed Jan 01 00:00:00 IST 2025