File tree Expand file tree Collapse file tree 3 files changed +35
-0
lines changed
test/java/com/baeldung/mapper Expand file tree Collapse file tree 3 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .baeldung .context ;
2
+
3
+ public class MappingContext {
4
+
5
+ public String normalizeName (String name ) {
6
+ return name == null ? null : name .trim ()
7
+ .toUpperCase ();
8
+ }
9
+ }
Original file line number Diff line number Diff line change 1
1
package com .baeldung .mapper ;
2
2
3
+ import org .mapstruct .AfterMapping ;
4
+ import org .mapstruct .Context ;
3
5
import org .mapstruct .Mapper ;
4
6
import org .mapstruct .Mapping ;
7
+ import org .mapstruct .MappingTarget ;
5
8
9
+ import com .baeldung .context .MappingContext ;
6
10
import com .baeldung .dto .CustomerDto ;
7
11
import com .baeldung .entity .Customer ;
8
12
@@ -12,4 +16,14 @@ public interface CustomerDtoMapper {
12
16
@ Mapping (source = "firstName" , target = "forename" )
13
17
@ Mapping (source = "lastName" , target = "surname" )
14
18
CustomerDto from (Customer customer );
19
+
20
+ @ Mapping (source = "firstName" , target = "forename" )
21
+ @ Mapping (source = "lastName" , target = "surname" )
22
+ CustomerDto from (Customer customer , @ Context MappingContext context );
23
+
24
+ @ AfterMapping
25
+ default void normalize (@ MappingTarget CustomerDto dto , @ Context MappingContext context ) {
26
+ dto .setForename (context .normalizeName (dto .getForename ()));
27
+ dto .setSurname (context .normalizeName (dto .getSurname ()));
28
+ }
15
29
}
Original file line number Diff line number Diff line change 5
5
import org .junit .jupiter .api .Test ;
6
6
import org .mapstruct .factory .Mappers ;
7
7
8
+ import com .baeldung .context .MappingContext ;
8
9
import com .baeldung .dto .CustomerDto ;
9
10
import com .baeldung .entity .Customer ;
10
11
@@ -26,4 +27,15 @@ void testGivenCustomer_mapsToCustomerDto() {
26
27
assertEquals (customerDto .getForename (), customer .getFirstName ());
27
28
assertEquals (customerDto .getSurname (), customer .getLastName ());
28
29
}
30
+
31
+ @ Test
32
+ void givenCustomer_whenMappedUsingContext_thenReturnsFormattedDto () {
33
+ Customer customer = new Customer ();
34
+ customer .setFirstName (" max " );
35
+ customer .setLastName (" powers " );
36
+ MappingContext context = new MappingContext ();
37
+ CustomerDto dto = customerDtoMapper .from (customer , context );
38
+ assertEquals ("MAX" , dto .getForename ());
39
+ assertEquals ("POWERS" , dto .getSurname ());
40
+ }
29
41
}
You can’t perform that action at this time.
0 commit comments