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 11package com .baeldung .mapper ;
22
3+ import org .mapstruct .AfterMapping ;
4+ import org .mapstruct .Context ;
35import org .mapstruct .Mapper ;
46import org .mapstruct .Mapping ;
7+ import org .mapstruct .MappingTarget ;
58
9+ import com .baeldung .context .MappingContext ;
610import com .baeldung .dto .CustomerDto ;
711import com .baeldung .entity .Customer ;
812
@@ -12,4 +16,14 @@ public interface CustomerDtoMapper {
1216 @ Mapping (source = "firstName" , target = "forename" )
1317 @ Mapping (source = "lastName" , target = "surname" )
1418 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+ }
1529}
Original file line number Diff line number Diff line change 55import org .junit .jupiter .api .Test ;
66import org .mapstruct .factory .Mappers ;
77
8+ import com .baeldung .context .MappingContext ;
89import com .baeldung .dto .CustomerDto ;
910import com .baeldung .entity .Customer ;
1011
@@ -26,4 +27,15 @@ void testGivenCustomer_mapsToCustomerDto() {
2627 assertEquals (customerDto .getForename (), customer .getFirstName ());
2728 assertEquals (customerDto .getSurname (), customer .getLastName ());
2829 }
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+ }
2941}
You can’t perform that action at this time.
0 commit comments